pax_global_header00006660000000000000000000000064137574300100014512gustar00rootroot0000000000000052 comment=be0896646a3f2d59dc1de4d149beb07c5b2c25c0 shellescape-1.4.1/000077500000000000000000000000001375743001000140055ustar00rootroot00000000000000shellescape-1.4.1/.github/000077500000000000000000000000001375743001000153455ustar00rootroot00000000000000shellescape-1.4.1/.github/workflows/000077500000000000000000000000001375743001000174025ustar00rootroot00000000000000shellescape-1.4.1/.github/workflows/build.yaml000066400000000000000000000012001375743001000213560ustar00rootroot00000000000000name: Build on: pull_request: push: branches: - main - master jobs: test: strategy: matrix: go-version: [1.14.x, 1.15.x] os: [ubuntu-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - name: Install Go uses: actions/setup-go@v2 with: go-version: 1.15 - name: Checkout code uses: actions/checkout@v2 - name: Build run: go build ./... - name: Test run: go test -race -cover -covermode=atomic -coverprofile=coverage.out ./... - uses: codecov/codecov-action@v1 with: file: ./coverage.out verbose: true shellescape-1.4.1/.github/workflows/golangci-lint.yml000066400000000000000000000014541375743001000226600ustar00rootroot00000000000000name: golangci-lint on: push: tags: - v* branches: - master - main pull_request: jobs: golangci: name: lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: golangci-lint uses: golangci/golangci-lint-action@v2 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.32 # 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.4.1/.github/workflows/release.yaml000066400000000000000000000010561375743001000217100ustar00rootroot00000000000000name: goreleaser on: pull_request: push: tags: - '*' jobs: goreleaser: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 with: fetch-depth: 0 - name: Set up Go uses: actions/setup-go@v2 with: go-version: 1.15 - name: Run GoReleaser uses: goreleaser/goreleaser-action@v2 with: version: latest args: release --rm-dist env: GITHUB_TOKEN: ${{ secrets.GORELEASER }} shellescape-1.4.1/.gitignore000066400000000000000000000004331375743001000157750ustar00rootroot00000000000000# 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 shellescape-1.4.1/.golangci.yml000066400000000000000000000023061375743001000163720ustar00rootroot00000000000000# run: # # timeout for analysis, e.g. 30s, 5m, default is 1m # timeout: 5m linters: disable-all: true enable: - bodyclose - deadcode - depguard - dogsled - goconst - gocritic - gofmt - goimports - golint - gosec - gosimple - govet - ineffassign - interfacer - maligned - misspell - prealloc - scopelint - staticcheck - structcheck - stylecheck - typecheck - unconvert - unparam - unused - misspell - 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 # FIXME: Disabled until golangci-lint updates stylecheck with this fix: # https://github.com/dominikh/go-tools/issues/389 - text: "ST1016:" linters: - stylecheck linters-settings: dogsled: max-blank-identifiers: 3 maligned: # print struct with more effective memory layout or not, false by default suggest-new: true run: tests: false shellescape-1.4.1/.goreleaser.yml000066400000000000000000000013171375743001000167400ustar00rootroot00000000000000# 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 main: ./cmd/escargs goos: - linux - windows - darwin archives: - replacements: darwin: Darwin linux: Linux windows: Windows 386: i386 amd64: x86_64 checksum: name_template: 'checksums.txt' snapshot: name_template: "{{ .Tag }}-next" changelog: sort: asc filters: exclude: - '^docs:' - '^test:' shellescape-1.4.1/AUTHORS000066400000000000000000000000451375743001000150540ustar00rootroot00000000000000Alessio Treglia shellescape-1.4.1/CODE_OF_CONDUCT.md000066400000000000000000000064261375743001000166140ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers 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, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at alessio@debian.org. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq shellescape-1.4.1/LICENSE000066400000000000000000000020721375743001000150130ustar00rootroot00000000000000The 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.4.1/README.md000066400000000000000000000042011375743001000152610ustar00rootroot00000000000000![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) [![Coverage](https://gocover.io/_badge/github.com/alessio/shellescape)](https://gocover.io/github.com/alessio/shellescape) [![Go Report Card](https://goreportcard.com/badge/github.com/alessio/shellescape)](https://goreportcard.com/report/github.com/alessio/shellescape) # 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" "gopkg.in/alessio/shellescape.v1" ) func main() { fmt.Printf("ls -l %s\n", shellescape.Quote(os.Args[1])) } ``` _[See in Go Playground](https://play.golang.org/p/HJ_CXgSrmp)_ ## The escargs utility __escargs__ reads lines from the standard input and prints shell-escaped versions. Unlinke __xargs__, blank lines on the standard input are not discarded. shellescape-1.4.1/cmd/000077500000000000000000000000001375743001000145505ustar00rootroot00000000000000shellescape-1.4.1/cmd/escargs/000077500000000000000000000000001375743001000161775ustar00rootroot00000000000000shellescape-1.4.1/cmd/escargs/escargs.go000066400000000000000000000032271375743001000201610ustar00rootroot00000000000000// escargs reads lines from the standard input and prints shell-escaped // versions. Unlinke xargs, blank lines on the standard input are not // discarded. package main import ( "bufio" "bytes" "flag" "fmt" "os" "github.com/alessio/shellescape" ) var ( discardBlankLines bool nullSeparator bool argFile string ) func main() { 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.Parse() firstScan := true scanner := bufio.NewScanner(os.Stdin) if argFile != "" { f, err := os.Open(argFile) if err != nil { fmt.Fprintf(os.Stderr, "escargs: %v\n", err) os.Exit(1) } scanner = bufio.NewScanner(f) } if nullSeparator { scanner.Split(splitNullTerminatedItems) } 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 splitNullTerminatedItems(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.4.1/example_test.go000066400000000000000000000032441375743001000170310ustar00rootroot00000000000000package shellescape_test import ( "fmt" "strings" "github.com/alessio/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() { 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 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: } shellescape-1.4.1/go.mod000066400000000000000000000000571375743001000151150ustar00rootroot00000000000000module github.com/alessio/shellescape go 1.14 shellescape-1.4.1/shellescape.go000066400000000000000000000031511375743001000166240ustar00rootroot00000000000000/* 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 gopkg.in/alessio/shellescape.v1" /* 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 ( "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) } shellescape-1.4.1/shellescape_test.go000066400000000000000000000035241375743001000176670ustar00rootroot00000000000000package shellescape_test import ( "testing" "github.com/alessio/shellescape" ) func assertEqual(t *testing.T, s, expected string) { if s != expected { t.Errorf("%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) } }) } }