pax_global_header00006660000000000000000000000064147574037340014530gustar00rootroot0000000000000052 comment=26fa1b3cc48d87f76ff79210a19ddd90de78660c shellescape-1.6.0/000077500000000000000000000000001475740373400140245ustar00rootroot00000000000000shellescape-1.6.0/.github/000077500000000000000000000000001475740373400153645ustar00rootroot00000000000000shellescape-1.6.0/.github/dependabot.yml000066400000000000000000000015141475740373400202150ustar00rootroot00000000000000# To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "gomod" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "daily" # Maintain dependencies for GitHub Actions # These would open PR, these PR would be tested with the CI # They will have to be merged manually by a maintainer - package-ecosystem: github-actions directory: / open-pull-requests-limit: 10 # avoid spam, if no one reacts schedule: interval: weekly time: '11:00'shellescape-1.6.0/.github/workflows/000077500000000000000000000000001475740373400174215ustar00rootroot00000000000000shellescape-1.6.0/.github/workflows/build.yaml000066400000000000000000000015071475740373400214070ustar00rootroot00000000000000name: Build on: pull_request: push: branches: - main - master jobs: test: strategy: matrix: go-version: [1.20.x, 1.21.x, 1.22.x, 1.23.x, 1.24.x] os: [ubuntu-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: go-version: ${{ matrix.go-version }} - name: Build run: go build -v ./... - name: Test run: go test -race ./... coverage: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: go-version: 'stable' - name: Coverage run: go test -race -cover -covermode=atomic -coverprofile=coverage.txt ./... - uses: codecov/codecov-action@v5 with: token: ${{ secrets.CODECOV_TOKEN }} shellescape-1.6.0/.github/workflows/codacy.yml000066400000000000000000000044631475740373400214150ustar00rootroot00000000000000# This workflow uses actions that are not certified by GitHub. # They are provided by a third-party and are governed by # separate terms of service, privacy policy, and support # documentation. # This workflow checks out code, performs a Codacy security scan # and integrates the results with the # GitHub Advanced Security code scanning feature. For more information on # the Codacy security scan action usage and parameters, see # https://github.com/codacy/codacy-analysis-cli-action. # For more information on Codacy Analysis CLI in general, see # https://github.com/codacy/codacy-analysis-cli. name: Codacy Security Scan on: push: branches: [ "master" ] pull_request: # The branches below must be a subset of the branches above branches: [ "master" ] schedule: - cron: '34 4 * * 2' permissions: contents: read jobs: codacy-security-scan: permissions: contents: read # for actions/checkout to fetch code security-events: write # for github/codeql-action/upload-sarif to upload SARIF results actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status name: Codacy Security Scan runs-on: ubuntu-latest steps: # Checkout the repository to the GitHub Actions runner - name: Checkout uses: actions/checkout@v4 # Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis - name: Codacy Analysis CLI uses: codacy/codacy-analysis-cli-action@v4 with: # Check https://github.com/codacy/codacy-analysis-cli#project-token to get your project token from your Codacy repository # You can also omit the token and run the tools that support default configurations verbose: true output: results.sarif format: sarif # Adjust severity of non-security issues gh-code-scanning-compat: true # Force 0 exit code to allow SARIF file generation # This will handover control about PR rejection to the GitHub side max-allowed-issues: 2147483647 # Upload the SARIF file generated in the previous step - name: Upload SARIF results file uses: github/codeql-action/upload-sarif@v3 with: sarif_file: results.sarif shellescape-1.6.0/.github/workflows/dependency-review.yml000066400000000000000000000015461475740373400235670ustar00rootroot00000000000000# Dependency Review Action # # This Action will scan dependency manifest files that change as part of a Pull Request, surfacing known-vulnerable versions of the packages declared or updated in the PR. Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable packages will be blocked from merging. # # Source repository: https://github.com/actions/dependency-review-action # Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement name: 'Dependency Review' on: [pull_request] permissions: contents: read jobs: dependency-review: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Dependency Review uses: actions/dependency-review-action@v4 shellescape-1.6.0/.github/workflows/golangci-lint.yml000066400000000000000000000016711475740373400227000ustar00rootroot00000000000000name: golangci-lint on: push: tags: - v* branches: - master - main pull_request: jobs: golangci: name: lint runs-on: ubuntu-latest steps: - name: checkout-action uses: actions/checkout@v4 - name: Set up Go uses: actions/setup-go@v5 with: go-version: 'stable' - name: golangci-lint uses: golangci/golangci-lint-action@v6 # with: # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. # version: v1.62 # Optional: working directory, useful for monorepos # working-directory: somedir # Optional: golangci-lint command line arguments. # args: --issues-exit-code=0 # Optional: show only new issues if it's a pull request. The default value is `false`. # only-new-issues: false shellescape-1.6.0/.github/workflows/release.yaml000066400000000000000000000010431475740373400217230ustar00rootroot00000000000000name: goreleaser on: push: tags: - '*' permissions: contents: write jobs: goreleaser: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - run: git fetch --force --tags - uses: actions/setup-go@v5 with: go-version: stable - uses: goreleaser/goreleaser-action@v6 with: distribution: goreleaser version: latest args: release --clean env: GITHUB_TOKEN: ${{ secrets.GORELEASER }} shellescape-1.6.0/.gitignore000066400000000000000000000004621475740373400160160ustar00rootroot00000000000000# Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *.test *.prof .idea/ escargs config.hcl .DS_Store shellescape-1.6.0/.golangci.yml000066400000000000000000000022361475740373400164130ustar00rootroot00000000000000# run: # # timeout for analysis, e.g. 30s, 5m, default is 1m # timeout: 5m linters: disable-all: true enable: - bodyclose - copyloopvar - dogsled - gci - goconst - gocritic - gofmt - goimports - gosec - gosimple - govet - ineffassign - misspell - prealloc - revive - staticcheck - stylecheck - typecheck - thelper - unconvert - unparam - unused - wsl issues: exclude-rules: - text: "Use of weak random number generator" linters: - gosec - text: "comment on exported var" linters: - golint - text: "don't use an underscore in package name" linters: - golint - text: "ST1003:" linters: - stylecheck - path: "_test.go" linters: - wsl linters-settings: dogsled: max-blank-identifiers: 3 # define the import orders gci: sections: # Standard section: captures all standard packages. - standard # Default section: catchall that is not standard or custom - default # linters that related to local tool, so they should be separated - localmodule shellescape-1.6.0/.goreleaser.yml000066400000000000000000000023171475740373400167600ustar00rootroot00000000000000# This is an example goreleaser.yaml file with some sane defaults. # Make sure to check the documentation at http://goreleaser.com before: hooks: # You may remove this if you don't use go modules. - go mod download # you may remove this if you don't need go generate - go generate ./... builds: - env: - CGO_ENABLED=0 - >- {{- if eq .Os "darwin" }} {{- if eq .Arch "amd64"}}CC=o64-clang{{- end }} {{- if eq .Arch "arm64"}}CC=aarch64-apple-darwin20.2-clang{{- end }} {{- end }} {{- if eq .Os "windows" }} {{- if eq .Arch "amd64" }}CC=x86_64-w64-mingw32-gcc{{- end }} {{- end }} main: ./cmd/escargs goos: - linux - windows - darwin - freebsd goarch: - amd64 - arm64 - arm goarm: - 6 - 7 goamd64: - v2 - v3 ignore: - goos: darwin goarch: 386 - goos: linux goarch: arm goarm: 7 - goarm: mips64 - gomips: hardfloat - goamd64: v4 checksum: name_template: 'checksums.txt' snapshot: name_template: "{{ .Tag }}-next" changelog: sort: asc filters: exclude: - '^docs:' - '^test:' shellescape-1.6.0/AUTHORS000066400000000000000000000000451475740373400150730ustar00rootroot00000000000000Alessio Treglia shellescape-1.6.0/CODE_OF_CONDUCT.md000066400000000000000000000126511475740373400166300ustar00rootroot00000000000000 # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [alessio AT debian DOT org][contact]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations [contact]: mailto:alessio_AT_debian_DOT_org shellescape-1.6.0/LICENSE000066400000000000000000000020721475740373400150320ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2016 Alessio Treglia 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. shellescape-1.6.0/Makefile000066400000000000000000000005371475740373400154710ustar00rootroot00000000000000 #!/usr/bin/make -f VERSION := $(shell git describe) all: build build: go build -a -v install: go install ./cmd/escargs escargs: build go build -v \ -ldflags="-X 'main.version=$(VERSION)'" \ ./cmd/escargs clean: rm -rfv escargs uninstall: rm -v $(shell go env GOPATH)/bin/escargs .PHONY: build clean install uninstall shellescape-1.6.0/README.md000066400000000000000000000040031475740373400153000ustar00rootroot00000000000000# shellescape ![Build](https://github.com/alessio/shellescape/workflows/Build/badge.svg) [![GoDoc](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/github.com/alessio/shellescape?tab=overview) [![sourcegraph](https://sourcegraph.com/github.com/alessio/shellescape/-/badge.svg)](https://sourcegraph.com/github.com/alessio/shellescape) [![codecov](https://codecov.io/gh/alessio/shellescape/branch/master/graph/badge.svg)](https://codecov.io/gh/alessio/shellescape) [![Go Report Card](https://goreportcard.com/badge/github.com/alessio/shellescape)](https://goreportcard.com/report/github.com/alessio/shellescape) Escape arbitrary strings for safe use as command line arguments. ## Contents of the package This package provides the `shellescape.Quote()` function that returns a shell-escaped copy of a string. This functionality could be helpful in those cases where it is known that the output of a Go program will be appended to/used in the context of shell programs' command line arguments. This work was inspired by the Python original package [shellescape](https://pypi.python.org/pypi/shellescape). ## Usage The following snippet shows a typical unsafe idiom: ```go package main import ( "fmt" "os" ) func main() { fmt.Printf("ls -l %s\n", os.Args[1]) } ``` _[See in Go Playground](https://play.golang.org/p/Wj2WoUfH_d)_ Especially when creating pipeline of commands which might end up being executed by a shell interpreter, it is particularly unsafe to not escape arguments. `shellescape.Quote()` comes in handy and to safely escape strings: ```go package main import ( "fmt" "os" "al.essio.dev/pkg/shellescape" ) func main() { fmt.Printf("ls -l %s\n", shellescape.Quote(os.Args[1])) } ``` _[See in Go Playground](https://go.dev/play/p/GeguukpSUTk)_ ## The escargs utility __escargs__ reads lines from the standard input and prints shell-escaped versions. Unlike __xargs__, blank lines on the standard input are not discarded. shellescape-1.6.0/cmd/000077500000000000000000000000001475740373400145675ustar00rootroot00000000000000shellescape-1.6.0/cmd/escargs/000077500000000000000000000000001475740373400162165ustar00rootroot00000000000000shellescape-1.6.0/cmd/escargs/escargs.go000066400000000000000000000036301475740373400201760ustar00rootroot00000000000000// escargs reads lines from the standard input and prints shell-escaped // versions. Unlike xargs, blank lines on the standard input are not // discarded. package main import ( "bufio" "flag" "fmt" "log" "os" "al.essio.dev/pkg/shellescape" ) var ( discardBlankLines bool nullSeparator bool argFile string helpMode bool versionMode bool ) var version = "UNRELEASED" func init() { flag.BoolVar(&discardBlankLines, "D", false, "ignore blank lines on the input stream.") flag.BoolVar(&nullSeparator, "0", false, "input items are terminated by a null character instead of by new line.") flag.StringVar(&argFile, "a", "", "read arguments from file, not standard input.") flag.BoolVar(&helpMode, "h", false, "display this help and exit.") flag.BoolVar(&versionMode, "V", false, "output version information and exit.") flag.Usage = usage flag.ErrHelp = nil } func main() { log.SetFlags(0) log.SetPrefix("escargs: ") log.SetOutput(os.Stderr) flag.Parse() if helpMode { usage() return } if versionMode { outputVersion() return } firstScan := true scanner := bufio.NewScanner(os.Stdin) if argFile != "" { f, err := os.Open(argFile) if err != nil { log.Fatal(err) } scanner = bufio.NewScanner(f) } if nullSeparator { scanner.Split(shellescape.ScanTokens) } for scanner.Scan() { line := scanner.Text() if discardBlankLines && len(line) == 0 { continue } if firstScan { firstScan = false } else { fmt.Printf(" ") } fmt.Printf("%s", shellescape.Quote(line)) } } func usage() { usageString := `Usage: escargs [-0ad] Escape arbitrary strings for safe use as command line arguments. Options:` _, _ = fmt.Fprintln(os.Stderr, usageString) flag.PrintDefaults() } func outputVersion() { fmt.Fprintf(os.Stderr, "escargs version %s\n", version) fmt.Fprintln(os.Stderr, "Copyright (C) 2020-2024 Alessio Treglia ") } shellescape-1.6.0/example_test.go000066400000000000000000000063411475740373400170510ustar00rootroot00000000000000package shellescape_test import ( "bufio" "fmt" "strings" "github.com/google/shlex" "al.essio.dev/pkg/shellescape" ) func ExampleQuote() { filename := "myfile; rm -rf /" prog := "/bin/ls -lh" unsafe := strings.Join([]string{prog, filename}, " ") safe := strings.Join([]string{prog, shellescape.Quote(filename)}, " ") fmt.Println("unsafe:", unsafe) fmt.Println("safe:", safe) for i, part := range strings.Split(unsafe, " ") { fmt.Printf("unsafe[%d] = %s\n", i, part) } for i, part := range strings.Split(safe, " ") { fmt.Printf("safe[%d] = %s\n", i, part) } // Output: // unsafe: /bin/ls -lh myfile; rm -rf / // safe: /bin/ls -lh 'myfile; rm -rf /' // unsafe[0] = /bin/ls // unsafe[1] = -lh // unsafe[2] = myfile; // unsafe[3] = rm // unsafe[4] = -rf // unsafe[5] = / // safe[0] = /bin/ls // safe[1] = -lh // safe[2] = 'myfile; // safe[3] = rm // safe[4] = -rf // safe[5] = /' } func ExampleQuoteCommand_simple() { filename := "filename with space" prog := "/usr/bin/ls" args := "-lh" unsafe := strings.Join([]string{prog, args, filename}, " ") safe := strings.Join([]string{prog, shellescape.QuoteCommand([]string{args, filename})}, " ") fmt.Println("unsafe:", unsafe) fmt.Println("safe:", safe) // Output: // unsafe: /usr/bin/ls -lh filename with space // safe: /usr/bin/ls -lh 'filename with space' } func ExampleQuoteCommand() { filename := "myfile; rm -rf /" unsafe := fmt.Sprintf("ls -l %s", filename) command := fmt.Sprintf("ls -l %s", shellescape.Quote(filename)) splitCommand, _ := shlex.Split(command) fmt.Println("unsafe:", unsafe) fmt.Println("command:", command) fmt.Println("splitCommand:", splitCommand) remoteCommandUnsafe := fmt.Sprintf("ssh host.domain %s", command) remoteCommand := fmt.Sprintf("ssh host.domain %s", shellescape.Quote(command)) splitRemoteCommand, _ := shlex.Split(remoteCommand) fmt.Println("remoteCommandUnsafe:", remoteCommandUnsafe) fmt.Println("remoteCommand:", remoteCommand) fmt.Println("splitRemoteCommand:", splitRemoteCommand) lastSplit, _ := shlex.Split(splitRemoteCommand[2]) fmt.Println("lastSplit[0]:", lastSplit[0]) fmt.Println("lastSplit[1]:", lastSplit[1]) fmt.Println("lastSplit[2]:", lastSplit[2]) // Output: // unsafe: ls -l myfile; rm -rf / // command: ls -l 'myfile; rm -rf /' // splitCommand: [ls -l myfile; rm -rf /] // remoteCommandUnsafe: ssh host.domain ls -l 'myfile; rm -rf /' // remoteCommand: ssh host.domain 'ls -l '"'"'myfile; rm -rf /'"'"'' // splitRemoteCommand: [ssh host.domain ls -l 'myfile; rm -rf /'] // lastSplit[0]: ls // lastSplit[1]: -l // lastSplit[2]: myfile; rm -rf / } func ExampleStripUnsafe() { safeString := `"printable!" #$%^characters '' 12321312"` unsafeString := "these runes shall be removed: \u0000\u0081\u001f" fmt.Println("safe:", shellescape.StripUnsafe(safeString)) fmt.Println("unsafe:", shellescape.StripUnsafe(unsafeString)) // Output: // safe: "printable!" #$%^characters '' 12321312" // unsafe: these runes shall be removed: } func ExampleScanTokens() { words := "'tis\x00but\x00a\x00scratch!\x00" scanner := bufio.NewScanner(strings.NewReader(words)) scanner.Split(shellescape.ScanTokens) for scanner.Scan() { fmt.Println(scanner.Text()) } // Output: // 'tis // but // a // scratch! } shellescape-1.6.0/go.mod000066400000000000000000000001611475740373400151300ustar00rootroot00000000000000module al.essio.dev/pkg/shellescape go 1.18 require github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 shellescape-1.6.0/go.sum000066400000000000000000000003351475740373400151600ustar00rootroot00000000000000github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= shellescape-1.6.0/shellescape.go000066400000000000000000000043451475740373400166510ustar00rootroot00000000000000/* Package shellescape provides the shellescape.Quote to escape arbitrary strings for a safe use as command line arguments in the most common POSIX shells. The original Python package which this work was inspired by can be found at https://pypi.python.org/pypi/shellescape. */ package shellescape // "import al.essio.dev/pkg/shellescape" /* The functionality provided by shellescape.Quote could be helpful in those cases where it is known that the output of a Go program will be appended to/used in the context of shell programs' command line arguments. */ import ( "bytes" "regexp" "strings" "unicode" ) var pattern *regexp.Regexp func init() { pattern = regexp.MustCompile(`[^\w@%+=:,./-]`) } // Quote returns a shell-escaped version of the string s. The returned value // is a string that can safely be used as one token in a shell command line. func Quote(s string) string { if len(s) == 0 { return "''" } if pattern.MatchString(s) { return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'" } return s } // QuoteCommand returns a shell-escaped version of the slice of strings. // The returned value is a string that can safely be used as shell command arguments. func QuoteCommand(args []string) string { l := make([]string, len(args)) for i, s := range args { l[i] = Quote(s) } return strings.Join(l, " ") } // StripUnsafe remove non-printable runes, e.g. control characters in // a string that is meant for consumption by terminals that support // control characters. func StripUnsafe(s string) string { return strings.Map(func(r rune) rune { if unicode.IsPrint(r) { return r } return -1 }, s) } // ScanTokens is a split function for a bufio.Scanner that returns each word of text, stripped // of amy trailing end-of-text empty byte. func ScanTokens(data []byte, atEOF bool) (advance int, token []byte, err error) { // Return nothing if at end-of-file and no data passed. if atEOF && len(data) == 0 { return 0, nil, nil } // Find the index of the input of a null character. if i := bytes.IndexByte(data, '\x00'); i >= 0 { return i + 1, data[0:i], nil } // If we're at EOF, we have a final, non-terminated line. Return it. if atEOF { return len(data), data, nil } // Request more data. return 0, nil, nil } shellescape-1.6.0/shellescape_test.go000066400000000000000000000045601475740373400177070ustar00rootroot00000000000000package shellescape_test import ( "bufio" "bytes" "testing" "al.essio.dev/pkg/shellescape" ) func assertEqual(t *testing.T, s, expected string) { t.Helper() if s != expected { t.Fatalf("%q (expected: %q)", s, expected) } } func TestEmptyString(t *testing.T) { s := shellescape.Quote("") expected := "''" assertEqual(t, s, expected) } func TestDoubleQuotedString(t *testing.T) { s := shellescape.Quote(`"double quoted"`) expected := `'"double quoted"'` assertEqual(t, s, expected) } func TestSingleQuotedString(t *testing.T) { s := shellescape.Quote(`'single quoted'`) expected := `''"'"'single quoted'"'"''` assertEqual(t, s, expected) } func TestUnquotedString(t *testing.T) { s := shellescape.Quote(`no quotes`) expected := `'no quotes'` assertEqual(t, s, expected) } func TestSingleInvalid(t *testing.T) { s := shellescape.Quote(`;`) expected := `';'` assertEqual(t, s, expected) } func TestAllInvalid(t *testing.T) { s := shellescape.Quote(`;${}`) expected := `';${}'` assertEqual(t, s, expected) } func TestCleanString(t *testing.T) { s := shellescape.Quote("foo.example.com") expected := `foo.example.com` assertEqual(t, s, expected) } func TestQuoteCommand(t *testing.T) { s := shellescape.QuoteCommand([]string{"ls", "-l", "file with space"}) expected := `ls -l 'file with space'` assertEqual(t, s, expected) } func TestStripUnsafe(t *testing.T) { type args struct { s string } tests := []struct { name string args args want string }{ {"all ASCII printable characters", args{`"printable!" characters '' 12321312"`}, `"printable!" characters '' 12321312"`}, {"some non printable characters", args{"print\u0081ble"}, "printble"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := shellescape.StripUnsafe(tt.args.s); got != tt.want { t.Errorf("StripUnsafe() = %v, want %v", got, tt.want) } }) } } func TestScanTokens(t *testing.T) { data := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")} buf := bytes.NewBuffer(bytes.Join(data, []byte{'\x00'})) want := []string{"foo", "bar", "baz"} scanner := bufio.NewScanner(buf) scanner.Split(shellescape.ScanTokens) for i := 0; scanner.Scan(); i++ { if got := scanner.Text(); got != want[i] { t.Errorf("scanner.Text() = %v, want %v", got, want[i]) } } if err := scanner.Err(); err != nil { t.Errorf("scanner.Err() = %v, want nil", err) } }