pax_global_header00006660000000000000000000000064144556207120014520gustar00rootroot0000000000000052 comment=36e49af430a368f2918ace4b4243aadc6629f082 shellescape-1.4.2/000077500000000000000000000000001445562071200140145ustar00rootroot00000000000000shellescape-1.4.2/.github/000077500000000000000000000000001445562071200153545ustar00rootroot00000000000000shellescape-1.4.2/.github/dependabot.yml000066400000000000000000000007671445562071200202160ustar00rootroot00000000000000# 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" shellescape-1.4.2/.github/workflows/000077500000000000000000000000001445562071200174115ustar00rootroot00000000000000shellescape-1.4.2/.github/workflows/build.yaml000066400000000000000000000011461445562071200213760ustar00rootroot00000000000000name: Build on: pull_request: push: branches: - main - master jobs: test: strategy: matrix: go-version: [1.19.x, 1.20.x] os: [ubuntu-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 - uses: actions/setup-go@v4 with: go-version: ${{ matrix.go-version }} - name: Build run: go build -v ./... - 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.2/.github/workflows/codacy.yml000066400000000000000000000045421445562071200214030ustar00rootroot00000000000000# 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 code uses: actions/checkout@v3 # Execute Codacy Analysis CLI and generate a SARIF output with the security issues identified during the analysis - name: Run Codacy Analysis CLI uses: codacy/codacy-analysis-cli-action@d840f886c4bd4edc059706d09c6a1586111c540b 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@v2 with: sarif_file: results.sarif shellescape-1.4.2/.github/workflows/dependency-review.yml000066400000000000000000000015651445562071200235600ustar00rootroot00000000000000# 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 Repository' uses: actions/checkout@v3 - name: 'Dependency Review' uses: actions/dependency-review-action@v3 shellescape-1.4.2/.github/workflows/golangci-lint.yml000066400000000000000000000016201445562071200226620ustar00rootroot00000000000000name: golangci-lint on: push: tags: - v* branches: - master - main pull_request: jobs: golangci: name: lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-go@v4 with: go-version: '1.20' cache: false - name: golangci-lint uses: golangci/golangci-lint-action@v3 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.53 # 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.2/.github/workflows/release.yaml000066400000000000000000000010431445562071200217130ustar00rootroot00000000000000name: goreleaser on: push: tags: - '*' permissions: contents: write jobs: goreleaser: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - run: git fetch --force --tags - uses: actions/setup-go@v4 with: go-version: stable - uses: goreleaser/goreleaser-action@v4 with: distribution: goreleaser version: latest args: release --clean env: GITHUB_TOKEN: ${{ secrets.GORELEASER }} shellescape-1.4.2/.gitignore000066400000000000000000000004331445562071200160040ustar00rootroot00000000000000# 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.2/.golangci.yml000066400000000000000000000021721445562071200164020ustar00rootroot00000000000000# run: # # timeout for analysis, e.g. 30s, 5m, default is 1m # timeout: 5m linters: disable-all: true enable: - bodyclose - dogsled - goconst - gocritic - gofmt - goimports - gosec - gosimple - govet - ineffassign - misspell - prealloc - exportloopref - revive - staticcheck - 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.2/.goreleaser.yml000066400000000000000000000023171445562071200167500ustar00rootroot00000000000000# 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.4.2/AUTHORS000066400000000000000000000000451445562071200150630ustar00rootroot00000000000000Alessio Treglia shellescape-1.4.2/CODE_OF_CONDUCT.md000066400000000000000000000064261445562071200166230ustar00rootroot00000000000000# 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.2/LICENSE000066400000000000000000000020721445562071200150220ustar00rootroot00000000000000The 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.2/README.md000066400000000000000000000042011445562071200152700ustar00rootroot00000000000000![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.2/cmd/000077500000000000000000000000001445562071200145575ustar00rootroot00000000000000shellescape-1.4.2/cmd/escargs/000077500000000000000000000000001445562071200162065ustar00rootroot00000000000000shellescape-1.4.2/cmd/escargs/escargs.go000066400000000000000000000046401445562071200201700ustar00rootroot00000000000000// 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" "log" "os" "github.com/alessio/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(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 } 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-2023 Alessio Treglia ") } shellescape-1.4.2/example_test.go000066400000000000000000000032441445562071200170400ustar00rootroot00000000000000package 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.2/go.mod000066400000000000000000000000571445562071200151240ustar00rootroot00000000000000module github.com/alessio/shellescape go 1.14 shellescape-1.4.2/shellescape.go000066400000000000000000000031511445562071200166330ustar00rootroot00000000000000/* 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.2/shellescape_test.go000066400000000000000000000035251445562071200176770ustar00rootroot00000000000000package 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) } }) } }