diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..f3cbbbf --- /dev/null +++ b/.editorconfig @@ -0,0 +1,23 @@ +# EditorConfig is awesome: https://EditorConfig.org +root = true + +[*] +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[{Makefile,go.mod,go.sum,*.go,*.templ,.gitmodules}] +charset = utf-8 +indent_style = tab +tab_width = 4 +indent_size = 4 + +[*.md] +indent_size = 4 +trim_trailing_whitespace = false + +eclint_indent_style = unset + +[Dockerfile] +indent_style = space +indent_size = 4 diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..704c0ff --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,13 @@ +version: 2 +updates: + - package-ecosystem: gomod + directory: / + schedule: + interval: weekly + allow: + - dependency-type: all + assignees: + - tsukinoko-kun + reviewers: + - tsukinoko-kun + target-branch: dev diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..2de0a26 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,89 @@ +# yaml-language-server: https://raw.githubusercontent.com/SchemaStore/schemastore/master/src/schemas/json/github-workflow.json +--- +name: goreleaser + +on: + create: + tags: + - "**" + +permissions: + contents: write + packages: write + # issues: write + +jobs: + test-mac: + runs-on: macos-latest + steps: + - name: Setup Go environment + uses: actions/setup-go@v5 + with: + go-version: stable + cache: true + architecture: x64 + - name: Checkout + uses: actions/checkout@v4 + - name: Build + run: go build ./... + - name: Test + run: go test ./... -v + test-win: + runs-on: windows-latest + steps: + - name: Setup Go environment + uses: actions/setup-go@v5 + with: + go-version: stable + cache: true + architecture: x64 + - name: Checkout + uses: actions/checkout@v4 + - name: Build + run: go build ./... + - name: Test + run: go test ./... -v + test-linux: + runs-on: ubuntu-latest + steps: + - name: Setup Go environment + uses: actions/setup-go@v5 + with: + go-version: stable + cache: true + architecture: x64 + - name: Checkout + uses: actions/checkout@v4 + - name: Build + run: go build ./... + - name: Test + run: go test ./... -v + + goreleaser: + needs: + - test-linux + - test-mac + - test-win + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: stable + # More assembly might be required: Docker logins, GPG, etc. + # It all depends on your needs. + - name: Run GoReleaser + uses: goreleaser/goreleaser-action@v5 + with: + # either 'goreleaser' (default) or 'goreleaser-pro' + distribution: goreleaser + version: ${{ env.GITHUB_REF_NAME }} + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.PUBLISH_TOKEN }} + # Your GoReleaser Pro key, if you are using the 'goreleaser-pro' distribution + # GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..61e9ddb --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with 'go test -c' +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# Go workspace file +go.work +go.work.sum + +# env file +.env + +# Editor config +**/.idea +**/.vs +**/.vscode +**/.fleet diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..e7e5bdf --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,35 @@ +# yaml-language-server: $schema=https://goreleaser.com/static/schema.json +--- +builds: + - binary: smash + goos: + - darwin + - linux + - windows + goarch: + - amd64 + - arm64 + env: + - CGO_ENABLED=0 + +checksum: + name_template: "checksums.txt" + algorithm: sha256 + +release: + prerelease: auto + +universal_binaries: + - replace: false + mod_timestamp: "{{ .CommitTimestamp }}" + +brews: + - name: smash + homepage: https://github.com/tsukinoko-kun/smash + description: Cross platform interactive shell + repository: + owner: tsukinoko-kun + name: homebrew-tap + commit_author: + name: tsukinoko-kun + email: gh@frankmayer.dev diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a80d4ff --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright 2024 Frank Mayer + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3158ad4 --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# smash + +cross platform interactive shell + +## install + +```shell +brew install tsukinoko-kun/tap/smash +``` + +```shell +go install github.com/tsukinoko-kun/smash@latest +``` diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..30fdf78 --- /dev/null +++ b/go.mod @@ -0,0 +1,33 @@ +module smash + +go 1.23.1 + +require ( + github.com/BurntSushi/toml v1.4.0 + github.com/charmbracelet/bubbles v0.20.0 + github.com/charmbracelet/bubbletea v1.1.1 + github.com/charmbracelet/lipgloss v0.13.0 + github.com/chzyer/readline v1.5.1 + github.com/mattn/go-shellwords v1.0.12 + github.com/tsukinoko-kun/calc v1.1.2 +) + +require ( + github.com/atotto/clipboard v0.1.4 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/x/ansi v0.2.3 // indirect + github.com/charmbracelet/x/term v0.2.0 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.15.2 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + golang.org/x/sync v0.8.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.3.8 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..9865615 --- /dev/null +++ b/go.sum @@ -0,0 +1,56 @@ +github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= +github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +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/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE= +github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU= +github.com/charmbracelet/bubbletea v1.1.1 h1:KJ2/DnmpfqFtDNVTvYZ6zpPFL9iRCRr0qqKOCvppbPY= +github.com/charmbracelet/bubbletea v1.1.1/go.mod h1:9Ogk0HrdbHolIKHdjfFpyXJmiCzGwy+FesYkZr7hYU4= +github.com/charmbracelet/lipgloss v0.13.0 h1:4X3PPeoWEDCMvzDvGmTajSyYPcZM4+y8sCA/SsA3cjw= +github.com/charmbracelet/lipgloss v0.13.0/go.mod h1:nw4zy0SBX/F/eAO1cWdcvy6qnkDUxr8Lw7dvFrAIbbY= +github.com/charmbracelet/x/ansi v0.2.3 h1:VfFN0NUpcjBRd4DnKfRaIRo53KRgey/nhOoEqosGDEY= +github.com/charmbracelet/x/ansi v0.2.3/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= +github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0= +github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0= +github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM= +github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ= +github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI= +github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk= +github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04= +github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +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-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/mattn/go-shellwords v1.0.12 h1:M2zGm7EW6UQJvDeQxo4T51eKPurbeFbe8WtebGE2xrk= +github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo= +github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +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/tsukinoko-kun/calc v1.1.2 h1:GyIo9AbI6LPFnwhCKotVatZpKpm5RdyJUMd/6konpdw= +github.com/tsukinoko-kun/calc v1.1.2/go.mod h1:AqS3zftRvG0H8NiP+HmDlZAlkEnl1mkrh0ZAc3tUIfo= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= diff --git a/internal/color/ansi.go b/internal/color/ansi.go new file mode 100644 index 0000000..295be4d --- /dev/null +++ b/internal/color/ansi.go @@ -0,0 +1,52 @@ +package color + +// Reset all attributes +const Reset = "\x1b[0m" + +// Foreground text colors +const ( + FgBlack = "\x1b[30m" + FgRed = "\x1b[31m" + FgGreen = "\x1b[32m" + FgYellow = "\x1b[33m" + FgBlue = "\x1b[34m" + FgMagenta = "\x1b[35m" + FgCyan = "\x1b[36m" + FgWhite = "\x1b[37m" +) + +// Foreground Hi-Intensity text colors +const ( + FgHiBlack = "\x1b[90m" + FgHiRed = "\x1b[91m" + FgHiGreen = "\x1b[92m" + FgHiYellow = "\x1b[93m" + FgHiBlue = "\x1b[94m" + FgHiMagenta = "\x1b[95m" + FgHiCyan = "\x1b[96m" + FgHiWhite = "\x1b[97m" +) + +// Background text colors +const ( + BgBlack = "\x1b[40m" + BgRed = "\x1b[41m" + BgGreen = "\x1b[42m" + BgYellow = "\x1b[43m" + BgBlue = "\x1b[44m" + BgMagenta = "\x1b[45m" + BgCyan = "\x1b[46m" + BgWhite = "\x1b[47m" +) + +// Background Hi-Intensity text colors +const ( + BgHiBlack = "\x1b[100m" + BgHiRed = "\x1b[101m" + BgHiGreen = "\x1b[102m" + BgHiYellow = "\x1b[103m" + BgHiBlue = "\x1b[104m" + BgHiMagenta = "\x1b[105m" + BgHiCyan = "\x1b[106m" + BgHiWhite = "\x1b[107m" +) diff --git a/internal/env/config.go b/internal/env/config.go new file mode 100644 index 0000000..29987a1 --- /dev/null +++ b/internal/env/config.go @@ -0,0 +1,125 @@ +package env + +import ( + "errors" + "fmt" + "os" + "path/filepath" + + "github.com/BurntSushi/toml" +) + +var ( + Config *smashConfig + Alias map[string][]string + HistoryFile string +) + +func init() { + loadVars() + HistoryFile = filepath.Join(getConfigDir(), "history.txt") + Config = getConfigFile() + if Config.Alias != nil { + Alias = make(map[string][]string, len(Config.Alias)) + for key, val := range Config.Alias { + switch v := val.(type) { + case string: + Alias[key] = []string{v} + case []any: + sArr := make([]string, len(v)) + for i, s := range v { + if s, ok := s.(string); ok { + sArr[i] = s + } else { + sArr[i] = fmt.Sprintf("%v", s) + } + } + Alias[key] = sArr + default: + Alias[key] = []string{fmt.Sprintf("%v", val)} + } + } + } else { + Alias = make(map[string][]string) + } +} + +type ( + smashColor struct { + CompletionText string `toml:"completion_text"` + CompletionSelectedBg string `toml:"completion_selected_bg"` + } + smashConfig struct { + InteractivePrompt string `toml:"ps1"` + LogPrompt string `toml:"ps2"` + Alias map[string]any `toml:"alias"` + Color smashColor `toml:"color"` + } +) + +func getConfigDir() string { + var d string + if xdgConfig, ok := os.LookupEnv("XDG_CONFIG_HOME"); ok { + d = filepath.Join(xdgConfig, "smash") + } else { + xdgConfig = filepath.Join(getUser().HomeDir, ".config") + if _, err := os.Stat(xdgConfig); err == nil { + d = filepath.Join(xdgConfig, "smash") + } else { + userConfig, err := os.UserConfigDir() + if err != nil { + panic(errors.Join(errors.New("failed to get user config dir"), err)) + } + d = filepath.Join(userConfig, "smash") + } + } + if err := os.MkdirAll(d, 0700); err != nil { + panic(errors.Join(errors.New("failed to create config dir"), err)) + } + return d +} + +func getConfigFile() *smashConfig { + p := filepath.Join(getConfigDir(), "config.toml") + c := &smashConfig{ + Alias: make(map[string]any), + Color: smashColor{ + CompletionText: "8", + CompletionSelectedBg: "4", + }, + } + if _, err := os.Stat(p); err != nil { + if os.IsNotExist(err) { + // create file + func() { + fmt.Printf("creating config file %s\n", p) + f, err := os.Create(p) + if err != nil { + panic(errors.Join(errors.New("failed to create config file"), err)) + } + defer f.Close() + c.InteractivePrompt = "${Color.FgHiBlack}$USER@$PWD\t$DEV${Color.Reset}\n${Color.FgBlue}❯${Color.Reset} " + c.LogPrompt = "${Color.FgHiBlack}$PWD${Color.Reset} " + c.Alias["l"] = []string{"ls", "-l"} + e := toml.NewEncoder(f) + if err := e.Encode(c); err != nil { + panic(errors.Join(errors.New("failed to write config file"), err)) + } + }() + } else { + panic(errors.Join(errors.New("failed to stat config file"), err)) + } + } + + f, err := os.Open(p) + if err != nil { + panic(errors.Join(errors.New("failed to open config file"), err)) + } + defer f.Close() + + d := toml.NewDecoder(f) + if _, err := d.Decode(c); err != nil { + panic(errors.Join(errors.New("failed to parse config file"), err)) + } + return c +} diff --git a/internal/env/profile_unix.go b/internal/env/profile_unix.go new file mode 100644 index 0000000..fbd788b --- /dev/null +++ b/internal/env/profile_unix.go @@ -0,0 +1,37 @@ +//go:build !windows + +package env + +import ( + "errors" + "fmt" + "os" + "os/exec" + "strings" +) + +func loadVars() { + shell := os.Getenv("SHELL") + if shell == "" { + shell = "/bin/sh" + } + cmd := exec.Command(shell, "-l", "-c", "env") + cmd.Stdin = os.Stdin + out, err := cmd.Output() + if err != nil { + panic(errors.Join(fmt.Errorf("failed to get env variables from shell %s", shell), err)) + } + + env := string(out) + env = env[:len(env)-1] + + for _, line := range strings.Split(env, "\n") { + parts := strings.SplitN(line, "=", 2) + if len(parts) != 2 { + continue + } + if err := os.Setenv(parts[0], parts[1]); err != nil { + panic(errors.Join(fmt.Errorf("failed to set env variable %s", parts[0]), err)) + } + } +} diff --git a/internal/env/profile_windows.go b/internal/env/profile_windows.go new file mode 100644 index 0000000..110c6b5 --- /dev/null +++ b/internal/env/profile_windows.go @@ -0,0 +1,7 @@ +//go:build windows + +package env + +func loadVars() { + // windows does that +} diff --git a/internal/env/user.go b/internal/env/user.go new file mode 100644 index 0000000..08e8021 --- /dev/null +++ b/internal/env/user.go @@ -0,0 +1,17 @@ +package env + +import "os/user" + +var u *user.User + +func getUser() *user.User { + if u != nil { + return u + } + var err error + u, err = user.Current() + if err != nil { + panic(err) + } + return u +} diff --git a/internal/gui/gui.go b/internal/gui/gui.go new file mode 100644 index 0000000..1157efa --- /dev/null +++ b/internal/gui/gui.go @@ -0,0 +1,214 @@ +package gui + +import ( + "fmt" + "strings" + + "smash/internal/env" + "smash/internal/shell" + + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" +) + +var ( + SelectedCompletionBg = lipgloss.Color(env.Config.Color.CompletionSelectedBg) + CompletionTextColor = lipgloss.Color(env.Config.Color.CompletionText) +) + +type model struct { + textInput textinput.Model + err error + lines int + prompt string + completions []shell.Completion + selectedComp int + showComp bool +} + +func initialModel() (*model, error) { + ti := textinput.New() + ti.Focus() + ti.CharLimit = 156 + ti.Prompt = "" // Remove the default '>' prompt + + prompt, err := shell.Ps1() + if err != nil { + return nil, fmt.Errorf("failed to get prompt: %w", err) + } + + return &model{ + textInput: ti, + err: nil, + lines: 0, + prompt: prompt, + }, nil +} + +func (m *model) Init() tea.Cmd { + return textinput.Blink +} + +func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + var cmd tea.Cmd + trimedInputValue := strings.TrimSpace(m.textInput.Value()) + + switch msg := msg.(type) { + case tea.KeyMsg: + switch msg.Type { + case tea.KeyTab: + shell.ResetHistoryIndex() + if !m.showComp { + if len(trimedInputValue) == 0 { + return m, nil + } + m.showComp = true + m.completions = shell.GetCompletions(m.textInput.Value()) + m.selectedComp = 0 + } else { + if len(m.completions) == 0 { + m.showComp = false + m.selectedComp = 0 + return m, nil + } else { + m.selectedComp = (m.selectedComp + 1) % len(m.completions) + } + } + return m, nil + case tea.KeyShiftTab: + if m.showComp { + m.selectedComp = (m.selectedComp - 1 + len(m.completions)) % len(m.completions) + } + return m, nil + case tea.KeyUp, tea.KeyDown: + if m.showComp { + if msg.Type == tea.KeyUp { + m.selectedComp = (m.selectedComp - 1 + len(m.completions)) % len(m.completions) + } else { + m.selectedComp = (m.selectedComp + 1) % len(m.completions) + } + return m, nil + } else { + var hisContent string + var hisOk bool + if msg.Type == tea.KeyUp { + hisContent, hisOk = shell.HistoryBack() + } else { + hisContent, hisOk = shell.HistoryForward() + } + if hisOk { + m.textInput.SetValue(hisContent) + m.textInput.CursorEnd() + } + } + case tea.KeyEsc: + if m.showComp { + m.showComp = false + return m, nil + } + case tea.KeyEnter: + shell.ResetHistoryIndex() + if m.showComp { + c := m.completions[m.selectedComp] + v := m.textInput.Value() + v = v[:len(v)-c.Delete] + c.Value + m.textInput.SetValue(v) + m.textInput.CursorEnd() + m.showComp = false + return m, nil + } + if m.textInput.Value() != "" { + return m, tea.Quit + } + case tea.KeyCtrlC: + shell.ResetHistoryIndex() + m.textInput.SetValue("") + return m, tea.Quit + } + } + + pre := m.textInput.Value() + m.textInput, cmd = m.textInput.Update(msg) + trimedInputValue = strings.TrimSpace(m.textInput.Value()) + + changed := pre != m.textInput.Value() + + if changed { + if m.showComp { + if len(trimedInputValue) == 0 { + m.showComp = false + m.completions = nil + } else { + newCompletions := shell.GetCompletions(m.textInput.Value()) + if !completionsEqual(m.completions, newCompletions) { + m.completions = newCompletions + m.selectedComp = 0 + } + } + } + shell.ResetHistoryIndex() + } + + return m, cmd +} + +// Helper function to compare two slices of completions +func completionsEqual(a, b []shell.Completion) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func (m *model) View() string { + if m.err != nil { + return fmt.Sprintf("Error: %v", m.err) + } + + view := lipgloss.NewStyle().Render(m.prompt + m.textInput.View()) + + if m.showComp { + view += "\n" + for i, comp := range m.completions { + style := lipgloss.NewStyle().Foreground(CompletionTextColor) + if i == m.selectedComp { + style = style.Background(SelectedCompletionBg) + } + view += style.Render(comp.String()) + "\n" + } + } + + m.lines = strings.Count(view, "\n") + + return view +} + +func RunPrompt() (string, error) { + SelectedCompletionBg = lipgloss.Color(env.Config.Color.CompletionSelectedBg) + CompletionTextColor = lipgloss.Color(env.Config.Color.CompletionText) + shell.ResetHistoryIndex() + + initialModel, err := initialModel() + if err != nil { + return "", err + } + + p := tea.NewProgram(initialModel) + + m, err := p.Run() + if err != nil { + return "", err + } + + // Clear only the lines we used + fmt.Printf("\033[%dA", m.(*model).lines) // Move cursor up + fmt.Printf("\033[J") // Clear from cursor to end of screen + + return strings.TrimSpace(m.(*model).textInput.Value()), nil +} diff --git a/internal/shell/completion.go b/internal/shell/completion.go new file mode 100644 index 0000000..ccc42ac --- /dev/null +++ b/internal/shell/completion.go @@ -0,0 +1,166 @@ +package shell + +import ( + "fmt" + "os" + "path/filepath" + "strings" +) + +type Completion struct { + Value string + DisplayText string + Delete int +} + +func (c Completion) String() string { + return fmt.Sprintf(" %s (%s) ", c.Value, c.DisplayText) +} + +const completionLimit = 24 + +func GetCompletions(input string) []Completion { + fields := strings.Fields(input) + if input[len(input)-1] == ' ' { + fields = append(fields, "") + } + switch len(fields) { + case 0: + return []Completion{} + case 1: + return getNameCompletion(input) + default: + return findWithPath(fields[len(fields)-1], false) + } +} + +func getNameCompletion(input string) []Completion { + completions := findWithPath(input, true) + + for _, tool := range internalToolNames { + if strings.HasPrefix(tool, input) { + completions = append(completions, Completion{Value: tool, DisplayText: "shell internal tool", Delete: len(input)}) + if len(completions) >= completionLimit { + return completions + } + } + } + if path, ok := os.LookupEnv("PATH"); ok { + outer: + for _, dir := range strings.Split(path, string(os.PathListSeparator)) { + d, err := os.ReadDir(dir) + if err != nil { + continue + } + for _, entry := range d { + if entry.IsDir() { + continue + } + if fileInfo, err := entry.Info(); err != nil || fileInfo.Mode()&0111 == 0 { + continue + } + n := entry.Name() + if !strings.HasPrefix(n, input) { + continue + } + completions = append(completions, Completion{Value: n, DisplayText: "executable in PATH", Delete: len(input)}) + if len(completions) >= completionLimit { + break outer + } + } + } + } + return completions +} + +func findWithPath(partialPath string, executable bool) []Completion { + var completions []Completion + + expandedPartialPath := os.ExpandEnv(partialPath) + if strings.HasPrefix(expandedPartialPath, "~") { + if home, err := os.UserHomeDir(); err == nil { + expandedPartialPath = home + expandedPartialPath[1:] + } + } + if strings.HasSuffix(partialPath, "/") { + if fi, err := os.Stat(expandedPartialPath); err != nil || !fi.IsDir() { + return completions + } + + // this is a directory, get its content + + entries, err := os.ReadDir(expandedPartialPath) + if err != nil { + return completions + } + for _, f := range entries { + c := Completion{ + Value: f.Name(), + Delete: 0, + } + + if f.IsDir() { + c.DisplayText = "directory" + c.Value += "/" + } else { + if executable { + if fi, err := f.Info(); err != nil || fi.Mode()&0111 == 0 { + continue + } + c.DisplayText = "executable file" + } else { + c.DisplayText = "file" + } + } + + completions = append(completions, c) + if len(completions) >= completionLimit { + return completions + } + } + } else { + // get matching paths inside the parent directory + + parentDir := filepath.Dir(expandedPartialPath) + entries, err := os.ReadDir(parentDir) + if err != nil { + return completions + } + partialFile := filepath.Base(expandedPartialPath) + + for _, f := range entries { + if !strings.HasPrefix(f.Name(), partialFile) { + continue + } + + c := Completion{ + Value: f.Name(), + Delete: len(partialFile), + } + + if f.IsDir() { + c.DisplayText = "directory" + c.Value += "/" + } else { + if executable { + if fi, err := f.Info(); err != nil || fi.Mode()&0111 == 0 { + continue + } + c.DisplayText = "executable file" + if partialPath[0] != '.' && partialPath[0] != '/' { + c.Value = "./" + c.Value + } + } else { + c.DisplayText = "file" + } + } + + completions = append(completions, c) + if len(completions) >= completionLimit { + return completions + } + } + } + + return completions +} diff --git a/internal/shell/history.go b/internal/shell/history.go new file mode 100644 index 0000000..336d7d3 --- /dev/null +++ b/internal/shell/history.go @@ -0,0 +1,104 @@ +package shell + +import ( + "bufio" + "fmt" + "os" + "smash/internal/env" +) + +const maxHistory = 512 + +var ( + history []string + currentIndex int +) + +func loadHistory() error { + file, err := os.OpenFile(env.HistoryFile, os.O_RDONLY|os.O_CREATE, 0644) + if err != nil { + return fmt.Errorf("failed to open history file: %w", err) + } + defer file.Close() + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + history = append(history, scanner.Text()) + if len(history) > maxHistory { + history = history[1:] + } + } + + currentIndex = len(history) + return scanner.Err() +} + +// HistoryBack goes one step back in the history and returns that entry +func HistoryBack() (string, bool) { + if len(history) == 0 { + if err := loadHistory(); err != nil { + return "", false + } + } + + if currentIndex > 0 { + currentIndex-- + return history[currentIndex], true + } + return "", false +} + +// HistoryForward goes one step forward in the history and returns that entry +func HistoryForward() (string, bool) { + if len(history) == 0 { + if err := loadHistory(); err != nil { + return "", false + } + } + + if currentIndex < len(history)-1 { + currentIndex++ + return history[currentIndex], true + } + currentIndex = len(history) + return "", true +} + +// AddToHistory adds a new entry to the history +func AddToHistory(entry string) error { + if len(history) == 0 { + if err := loadHistory(); err != nil { + return err + } + } + + if len(history) != 0 { + latestHistoryEntry := history[len(history)-1] + if latestHistoryEntry == entry { + return nil + } + } + + history = append(history, entry) + if len(history) > maxHistory { + history = history[1:] + } + currentIndex = len(history) + + // Append to file + file, err := os.OpenFile(env.HistoryFile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) + if err != nil { + return fmt.Errorf("failed to open history file: %w", err) + } + defer file.Close() + + if _, err := fmt.Fprintln(file, entry); err != nil { + return fmt.Errorf("failed to write to history file: %w", err) + } + + return nil +} + +func ResetHistoryIndex() { + currentIndex = len(history) +} diff --git a/internal/shell/input.go b/internal/shell/input.go new file mode 100644 index 0000000..da5c1c4 --- /dev/null +++ b/internal/shell/input.go @@ -0,0 +1,349 @@ +package shell + +import ( + "fmt" + "github.com/mattn/go-shellwords" + "io" + "os" + "path/filepath" + "sync" +) + +type ( + command interface { + Run(stdin io.Reader, stdout io.Writer, stderr io.Writer) error + SetName(name string) + SetArgs(args []string) + And() command + Or() command + Pipe() command + Parallel() + IsParallel() bool + } + + exe struct { + name string + args []string + parallel bool + } + + and struct { + commands []command + current command + parallel bool + } + + or struct { + commands []command + current command + parallel bool + } + + pipe struct { + from command + to command + parallel bool + } +) + +func expand(s string) string { + if len(s) == 0 { + return s + } + s = os.ExpandEnv(s) + if s[0] == '~' { + ss := u.HomeDir + s[1:] + if _, err := os.Stat(ss); err == nil { + s = filepath.Clean(ss) + } + } else if _, err := os.Stat(s); err == nil { + s = filepath.Clean(s) + } + return s +} + +func expandArray(arr []string) []string { + if arr == nil { + return nil + } + for i, s := range arr { + arr[i] = expand(s) + } + return arr +} + +func Parse(s string) ([]command, error) { + commands := make([]command, 0) + var currentCommand command = &exe{} + commands = append(commands, currentCommand) + + parser := shellwords.NewParser() + for { + args, err := parser.Parse(s) + if err != nil { + return nil, err + } + + switch len(args) { + case 0: + break + case 1: + currentCommand.SetName(expand(args[0])) + default: + currentCommand.SetName(expand(args[0])) + currentCommand.SetArgs(expandArray(args[1:])) + } + + if parser.Position < 0 { + break + } + + i := parser.Position + for ; i < len(s); i++ { + if isSpace(s[i]) { + break + } + } + if next, err := shift(&commands, currentCommand, string([]rune(s)[parser.Position:i])); err != nil { + return nil, err + } else { + currentCommand = next + } + if i >= len(s) { + break + } else { + s = string([]rune(s)[i+1:]) + } + } + + return commands, nil +} + +func shift(commands *[]command, current command, token string) (command, error) { + switch token { + case "&&": + i := len(*commands) - 1 + next := current.And() + (*commands)[i] = next + return next, nil + case "||": + i := len(*commands) - 1 + next := current.Or() + (*commands)[i] = next + return next, nil + case "|": + i := len(*commands) - 1 + next := current.Pipe() + (*commands)[i] = next + return next, nil + case "&": + current.Parallel() + next := &exe{} + *commands = append(*commands, next) + return next, nil + case ";": + next := &exe{} + *commands = append(*commands, next) + return next, nil + default: + return nil, fmt.Errorf("unexpected token: %s", token) + } +} + +func isSpace(r byte) bool { + switch r { + case ' ', '\t', '\r', '\n', '\v': + return true + } + return false +} + +func (e *exe) SetName(name string) { + e.name = name +} + +func (a *and) SetName(name string) { + a.current.SetName(name) +} + +func (o *or) SetName(name string) { + o.current.SetName(name) +} + +func (p *pipe) SetName(name string) { + p.to.SetName(name) +} + +func (e *exe) SetArgs(args []string) { + e.args = args +} + +func (a *and) SetArgs(args []string) { + a.current.SetArgs(args) +} + +func (o *or) SetArgs(args []string) { + o.current.SetArgs(args) +} + +func (p *pipe) SetArgs(args []string) { + p.to.SetArgs(args) +} + +func (e *exe) And() command { + next := &exe{} + a := &and{current: next, commands: []command{e, next}} + return a +} + +func (a *and) And() command { + a.current = &exe{} + a.commands = append(a.commands, a.current) + return a +} + +func (o *or) And() command { + i := len(o.commands) - 1 + next := &exe{} + a := &and{current: next, commands: []command{o, o.commands[i], next}} + o.current = nil + o.commands = o.commands[:i] + return a +} + +func (p *pipe) And() command { + next := &exe{} + a := &and{current: next, commands: []command{p, next}} + return a +} + +func (e *exe) Or() command { + next := &exe{} + o := &or{current: next, commands: []command{e, next}} + return o +} + +func (a *and) Or() command { + next := &exe{} + o := &or{current: next, commands: []command{a, next}} + a.current = nil + return o +} + +func (o *or) Or() command { + o.current = &exe{} + o.commands = append(o.commands, o.current) + return o +} + +func (p *pipe) Or() command { + next := &exe{} + return &or{current: next, commands: []command{p, next}} +} + +func (e *exe) Pipe() command { + return &pipe{from: e, to: &exe{}} +} + +func (a *and) Pipe() command { + a.current = &pipe{from: a.current, to: &exe{}} + a.commands[len(a.commands)-1] = a.current + return a +} + +func (o *or) Pipe() command { + o.current = &pipe{from: o.current, to: &exe{}} + o.commands[len(o.commands)-1] = o.current + return o +} + +func (p *pipe) Pipe() command { + return &pipe{from: p, to: &exe{}} +} + +func (a *and) Run(stdin io.Reader, stdout io.Writer, stderr io.Writer) error { + for _, cmd := range a.commands { + if err := cmd.Run(stdin, stdout, stderr); err != nil { + return err + } + } + return nil +} + +func (o *or) Run(stdin io.Reader, stdout io.Writer, stderr io.Writer) error { + for _, cmd := range o.commands { + if err := cmd.Run(stdin, stdout, stderr); err == nil { + return nil + } + } + return fmt.Errorf("smash: all commands in or failed") +} + +func (p *pipe) Run(stdin io.Reader, stdout io.Writer, stderr io.Writer) error { + stdoutReader, stdoutWriter := io.Pipe() + + var fromErr error + var toErr error + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer wg.Done() + defer stdoutWriter.Close() + fromErr = p.from.Run(stdin, stdoutWriter, stderr) + }() + + go func() { + defer wg.Done() + toErr = p.to.Run(stdoutReader, stdout, stderr) + }() + + wg.Wait() + + if fromErr != nil { + return fromErr + } + return toErr +} + +func (e *exe) Parallel() { + e.parallel = true +} + +func (a *and) Parallel() { + a.parallel = true +} + +func (o *or) Parallel() { + o.parallel = true +} + +func (p *pipe) Parallel() { + p.parallel = true +} + +func (e *exe) IsParallel() bool { + return e.parallel +} + +func (a *and) IsParallel() bool { + return a.parallel +} + +func (o *or) IsParallel() bool { + return o.parallel +} + +func (p *pipe) IsParallel() bool { + return p.parallel +} + +func RunCommand(c command, stdin io.Reader, stdout io.Writer, stderr io.Writer) error { + if c.IsParallel() { + go c.Run(stdin, stdout, stderr) + return nil + } else { + return c.Run(stdin, stdout, stderr) + } +} diff --git a/internal/shell/listener.go b/internal/shell/listener.go new file mode 100644 index 0000000..1468523 --- /dev/null +++ b/internal/shell/listener.go @@ -0,0 +1,17 @@ +package shell + +import ( + "github.com/chzyer/readline" +) + +type Listener struct { + rl *readline.Instance +} + +func (l *Listener) SetReadline(rl *readline.Instance) { + l.rl = rl +} + +func (l *Listener) OnChange(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool) { + return line, pos, false +} diff --git a/internal/shell/ps1.go b/internal/shell/ps1.go new file mode 100644 index 0000000..481c6d0 --- /dev/null +++ b/internal/shell/ps1.go @@ -0,0 +1,238 @@ +package shell + +import ( + "bufio" + "errors" + "os" + "os/exec" + "os/user" + "path/filepath" + "smash/internal/color" + "smash/internal/env" + "strings" + "sync" +) + +var u *user.User + +func init() { + var err error + u, err = user.Current() + if err != nil { + panic(err) + } +} + +type dirInfo struct { + Wd string + Dev string +} + +func getDirInfo(wd string) dirInfo { + di := dirInfo{ + Wd: wd, + } + + wg := sync.WaitGroup{} + dev := [4]string{} + wg.Add(len(dev)) + go func() { + defer wg.Done() + dev[0] = dirInfoGit(wd) + }() + go func() { + defer wg.Done() + dev[1] = dirInfoDocker(wd) + }() + go func() { + defer wg.Done() + dev[2] = dirInfoGo(wd) + }() + go func() { + defer wg.Done() + dev[3] = dirInfoJavascript(wd) + }() + wg.Wait() + + sb := strings.Builder{} + for _, d := range dev { + if d != "" { + sb.WriteString(d) + sb.WriteString(" ") + } + } + di.Dev = sb.String() + return di +} + +func dirInfoGit(wd string) string { + // run git to get current branch + cmd := exec.Command("git", "branch", "--show-current") + cmd.Dir = wd + out, err := cmd.Output() + if err != nil { + return "" + } + return color.FgGreen + "\U000F02A2 " + strings.TrimSpace(string(out)) + color.Reset +} + +func dirInfoDocker(wd string) string { + found := false + dirEntries, err := os.ReadDir(wd) + if err != nil { + return "" + } + for _, d := range dirEntries { + if d.IsDir() { + continue + } + if strings.HasSuffix(d.Name(), "Dockerfile") || + strings.HasSuffix(d.Name(), "docker-compose.yml") || + strings.HasSuffix(d.Name(), "docker-compose.toml") { + found = true + break + } + } + if found { + return color.FgCyan + "\U000F0868" + color.Reset + } else { + return "" + } +} + +func dirInfoGo(wd string) string { + goModPath := filepath.Join(wd, "go.mod") + f, err := os.Open(goModPath) + if err != nil { + return "" + } + defer f.Close() + + // try to find versino e.g. go 1.23.1 + scanner := bufio.NewScanner(f) + for scanner.Scan() { + line := scanner.Text() + if strings.HasPrefix(line, "go ") { + return color.FgBlue + "\uE627 " + line[3:] + color.Reset + } + } + return "" +} + +func dirInfoJavascript(wd string) string { + if _, err := os.Stat(filepath.Join(wd, "package.json")); err == nil { + return color.FgYellow + "\U000F031E" + color.Reset + } + return "" +} + +func (di dirInfo) Expand(s string) string { + switch s { + case "DEV": + return di.Dev + case "PWD": + return di.Wd + case "USER": + return u.Username + + // Color Reset + case "Color.Reset": + return color.Reset + + // Color Foreground + case "Color.FgBlack": + return color.FgBlack + case "Color.FgRed": + return color.FgRed + case "Color.FgGreen": + return color.FgGreen + case "Color.FgYellow": + return color.FgYellow + case "Color.FgBlue": + return color.FgBlue + case "Color.FgMagenta": + return color.FgMagenta + case "Color.FgCyan": + return color.FgCyan + case "Color.FgWhite": + return color.FgWhite + + case "Color.FgHiBlack": + return color.FgHiBlack + case "Color.FgHiRed": + return color.FgHiRed + case "Color.FgHiGreen": + return color.FgHiGreen + case "Color.FgHiYellow": + return color.FgHiYellow + case "Color.FgHiBlue": + return color.FgHiBlue + case "Color.FgHiMagenta": + return color.FgHiMagenta + case "Color.FgHiCyan": + return color.FgHiCyan + case "Color.FgHiWhite": + return color.FgHiWhite + + // Color Background + case "Color.BgBlack": + return color.BgBlack + case "Color.BgRed": + return color.BgRed + case "Color.BgGreen": + return color.BgGreen + case "Color.BgYellow": + return color.BgYellow + case "Color.BgBlue": + return color.BgBlue + case "Color.BgMagenta": + return color.BgMagenta + case "Color.BgCyan": + return color.BgCyan + case "Color.BgWhite": + return color.BgWhite + + case "Color.BgHiBlack": + return color.BgHiBlack + case "Color.BgHiRed": + return color.BgHiRed + case "Color.BgHiGreen": + return color.BgHiGreen + case "Color.BgHiYellow": + return color.BgHiYellow + case "Color.BgHiBlue": + return color.BgHiBlue + case "Color.BgHiMagenta": + return color.BgHiMagenta + case "Color.BgHiCyan": + return color.BgHiCyan + case "Color.BgHiWhite": + return color.BgHiWhite + + } + return os.Getenv(s) +} + +func Ps1() (string, error) { + wd, err := os.Getwd() + if err != nil { + return "", errors.Join(errors.New("could not get working directory"), err) + } + di := getDirInfo(wd) + if strings.HasPrefix(wd, u.HomeDir) { + di.Wd = filepath.Join("~", wd[len(u.HomeDir):]) + } + return os.Expand(env.Config.InteractivePrompt, di.Expand), nil +} + +func Ps2() (string, error) { + wd, err := os.Getwd() + if err != nil { + return "", errors.Join(errors.New("could not get working directory"), err) + } + di := getDirInfo(wd) + if strings.HasPrefix(wd, u.HomeDir) { + di.Wd = filepath.Join("~", wd[len(u.HomeDir):]) + } + return os.Expand(env.Config.LogPrompt, di.Expand), nil +} diff --git a/internal/shell/run.go b/internal/shell/run.go new file mode 100644 index 0000000..d6d87ec --- /dev/null +++ b/internal/shell/run.go @@ -0,0 +1,264 @@ +package shell + +import ( + "errors" + "fmt" + "github.com/tsukinoko-kun/calc/calc" + "io" + "net/url" + "os" + "os/exec" + "smash/internal/env" + "strconv" + "strings" + "sync" + "time" +) + +func Run(s string) error { + defer func() { + if r := recover(); r != nil { + issueUrl, _ := url.Parse("https://github.com/tsukinoko-kun/smash/issues/new") + q := issueUrl.Query() + q.Add("title", "panic on command execution") + q.Add("body", fmt.Sprintf("command:\n```shell\n%s\n```\n\nerror:\n```\n%v\n```\n", s, r)) + issueUrl.RawQuery = q.Encode() + _, _ = fmt.Fprintf(os.Stderr, "smash: %v\nplease report this: %s\n", r, issueUrl.String()) + } + }() + Cancel() + commands, err := Parse(s) + if err != nil { + return errors.Join(fmt.Errorf("failed to parse: %s", s), err) + } + + for _, c := range commands { + _ = RunCommand(c, os.Stdin, os.Stdout, os.Stderr) + } + + return nil +} + +func (e *exe) Run(stdin io.Reader, stdout io.Writer, stderr io.Writer) error { + if e.name == "" { + return nil + } + if alias, ok := env.Alias[e.name]; ok { + switch len(alias) { + case 0: + panic(fmt.Sprintf("invalid alias %s = %v", e.name, alias)) + case 1: + e.name = alias[0] + default: + e.name = alias[0] + e.args = append(alias[1:], e.args...) + } + } + if ok, err := e.internal(stdin, stdout, stderr); ok { + if err != nil { + _, _ = fmt.Fprintln(stderr, err.Error()) + } + return err + } else { + cmd := exec.Command(e.name, e.args...) + cmd.Stdin = stdin + cmd.Stdout = stdout + cmd.Stderr = stderr + var err error + if e.parallel { + err = cmd.Run() + } else { + i := trackRunning(cmd) + err = cmd.Run() + untrack(i) + } + if err != nil { + _, _ = fmt.Fprintln(stderr, err.Error()) + } + return err + } +} + +var ( + running []*exec.Cmd + runningMut sync.Mutex +) + +func trackRunning(cmd *exec.Cmd) int { + runningMut.Lock() + defer runningMut.Unlock() + running = append(running, cmd) + return len(running) - 1 +} + +func untrack(i int) { + runningMut.Lock() + defer runningMut.Unlock() + running[i] = nil +} + +func Cancel() { + runningMut.Lock() + defer runningMut.Unlock() + for _, cmd := range running { + if cmd == nil || cmd.Process == nil { + continue + } + + if cmd.ProcessState != nil && cmd.ProcessState.Exited() { + continue + } + + err := cmd.Process.Signal(os.Interrupt) + if err != nil { + _, _ = fmt.Fprintf(os.Stderr, "failed to send interrupt signal: %v\n", err) + } + } + running = nil +} + +func (e *exe) exit() error { + if len(e.args) == 0 { + os.Exit(0) + } else { + exitCode, err := strconv.Atoi(e.args[0]) + if err != nil { + return fmt.Errorf("exit: Illegal number: %s", e.args[0]) + } + os.Exit(exitCode) + } + return nil +} + +func (e *exe) echo(stdout io.Writer) error { + if len(e.args) == 0 { + _, _ = fmt.Fprintln(stdout) + } else { + _, _ = fmt.Fprintln(stdout, strings.Join(e.args, " ")) + } + return nil +} + +func (e *exe) printf(stdout io.Writer) error { + switch len(e.args) { + case 0: + return errors.New("printf: usage: printf format [arg ...]") + case 1: + _, _ = fmt.Fprintln(stdout, e.args[0]) + default: + arg := make([]any, len(e.args)-1) + for i, a := range e.args[1:] { + arg[i] = a + } + _, _ = fmt.Fprintf(stdout, e.args[0], arg...) + } + return nil +} + +func (e *exe) time(stdout io.Writer, stderr io.Writer) error { + if len(e.args) == 0 { + return nil + } + + var cmd *exec.Cmd + if len(e.args) == 1 { + cmd = exec.Command(e.args[0]) + } else { + cmd = exec.Command(e.args[0], e.args[1:]...) + } + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + start := time.Now() + err := cmd.Run() + end := time.Now() + if err != nil { + _, _ = fmt.Fprintln(stderr, err.Error()) + } + _, _ = fmt.Fprintf(stdout, "\treal %v\n", end.Sub(start)) + return err +} + +func (e *exe) calc(stdin io.Reader, stdout io.Writer) error { + if len(e.args) == 0 { + // read string from stdin + sb := strings.Builder{} + _, _ = io.Copy(&sb, stdin) + root, err := calc.Ast(calc.Tokenize(strings.TrimSpace(sb.String()))) + if err != nil { + return err + } + if v, err := root.Eval(); err != nil { + return err + } else { + _, _ = fmt.Fprintf(stdout, "%v\n", v) + return nil + } + } else { + // read args + root, err := calc.Ast(calc.Tokenize(strings.Join(e.args, ""))) + if err != nil { + return err + } + if v, err := root.Eval(); err != nil { + return err + } else { + _, _ = fmt.Fprintf(stdout, "%v\n", v) + return nil + } + } +} + +var ( + cdHistory []string + cdHistoryMut sync.Mutex +) + +func popDir() error { + cdHistoryMut.Lock() + defer cdHistoryMut.Unlock() + if len(cdHistory) == 0 { + return nil + } + lastCd := cdHistory[len(cdHistory)-1] + cdHistory = cdHistory[:len(cdHistory)-1] + if err := os.Chdir(lastCd); err != nil { + return err + } else { + _ = os.Setenv("PWD", lastCd) + return nil + } +} + +func pushDir(p string) error { + cdHistoryMut.Lock() + defer cdHistoryMut.Unlock() + + wd, err := os.Getwd() + if err != nil { + return err + } + cdHistory = append(cdHistory, wd) + + if err := os.Chdir(p); err != nil { + return err + } else { + _ = os.Setenv("PWD", p) + return nil + } +} + +func (e *exe) cd() error { + switch len(e.args) { + case 0: + return pushDir(u.HomeDir) + case 1: + if e.args[0] == "-" { + return popDir() + } else { + return pushDir(e.args[0]) + } + default: + return pushDir(strings.Join(e.args, " ")) + } +} diff --git a/internal/shell/shell_unix.go b/internal/shell/shell_unix.go new file mode 100644 index 0000000..642276e --- /dev/null +++ b/internal/shell/shell_unix.go @@ -0,0 +1,33 @@ +//go:build !windows + +package shell + +import "io" + +var internalToolNames = [...]string{ + "exit", + "echo", + "printf", + "time", + "calc", + "cd", +} + +func (e *exe) internal(stdin io.Reader, stdout io.Writer, stderr io.Writer) (bool, error) { + switch e.name { + case "exit": + return true, e.exit() + case "echo": + return true, e.echo(stdout) + case "printf": + return true, e.printf(stdout) + case "time": + return true, e.time(stdout, stderr) + case "calc": + return true, e.calc(stdin, stdout) + case "cd": + return true, e.cd() + default: + return false, nil + } +} diff --git a/internal/shell/shell_windows.go b/internal/shell/shell_windows.go new file mode 100644 index 0000000..7164566 --- /dev/null +++ b/internal/shell/shell_windows.go @@ -0,0 +1,49 @@ +package shell + +import ( + "fmt" + "io" + "os" + "strings" +) + +var internalToolNames = [...]string{ + "exit", + "echo", + "printf", + "time", + "calc", + "cd", + "env", +} + +func (e *exe) internal(stdin io.Reader, stdout io.Writer, stderr io.Writer) (bool, error) { + switch e.name { + case "exit": + return true, e.exit() + case "echo": + return true, e.echo(stdout) + case "printf": + return true, e.printf(stdout) + case "time": + return true, e.time(stdout, stderr) + case "calc": + return true, e.calc(stdin, stdout) + case "cd": + return true, e.cd() + case "env": + return true, e.env(stdout) + default: + return false, nil + } +} + +func (e *exe) env(stdout io.Writer) error { + sb := strings.Builder{} + for _, e := range os.Environ() { + sb.WriteString(e) + sb.WriteRune('\n') + } + _, _ = fmt.Fprint(stdout, sb.String()) + return nil +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..9b6505d --- /dev/null +++ b/main.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" + "os" + "os/signal" + "smash/internal/gui" + "smash/internal/shell" +) + +func main() { + sigint := make(chan os.Signal, 1) + signal.Notify(sigint, os.Interrupt) + + go func() { + for range sigint { + <-sigint + shell.Cancel() + } + }() + + defer close(sigint) + + for { + if userInput, err := gui.RunPrompt(); err != nil { + fmt.Printf("gui error: %v\n", err) + } else { + if userInput == "" { + continue + } + _ = shell.AddToHistory(userInput) + ps2, err := shell.Ps2() + if err != nil { + fmt.Printf("ps2 error: %v\n", err) + } else { + fmt.Println(ps2 + userInput) + } + if err := shell.Run(userInput); err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + } + } + } +}