pax_global_header00006660000000000000000000000064146234771270014527gustar00rootroot0000000000000052 comment=aa6c6f4f24d60f9bec3b6ef7c6f29cf65dbcab82 puppetlabs-clj-shell-utils-f5155d1/000077500000000000000000000000001462347712700172535ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/.github/000077500000000000000000000000001462347712700206135ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/.github/workflows/000077500000000000000000000000001462347712700226505ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/.github/workflows/snyk.yml000066400000000000000000000034471462347712700243670ustar00rootroot00000000000000name: mend_scan on: workflow_dispatch: push: branches: - main jobs: build: runs-on: ubuntu-latest steps: - name: connect_twingate uses: twingate/github-action@v1 with: service-key: ${{ secrets.TWINGATE_PUBLIC_REPO_KEY }} - name: checkout repo content uses: actions/checkout@v2 # checkout the repository content to github runner. with: fetch-depth: 1 # install java which is required for mend and clojure - name: setup java uses: actions/setup-java@v3 with: distribution: temurin java-version: 17 # install clojure tools - name: Install Clojure tools uses: DeLaGuardo/setup-clojure@10.1 with: # Install just one or all simultaneously # The value must indicate a particular version of the tool, or use 'latest' # to always provision the latest version cli: latest # Clojure CLI based on tools.deps lein: latest # Leiningen boot: latest # Boot.clj bb: latest # Babashka clj-kondo: latest # Clj-kondo cljstyle: latest # cljstyle zprint: latest # zprint # run lein gen - name: create pom.xml run: lein pom # download mend - name: download_mend run: curl -o wss-unified-agent.jar https://unified-agent.s3.amazonaws.com/wss-unified-agent.jar - name: run mend run: env WS_INCLUDES=pom.xml java -jar wss-unified-agent.jar env: WS_APIKEY: ${{ secrets.MEND_API_KEY }} WS_WSS_URL: https://saas-eu.whitesourcesoftware.com/agent WS_USERKEY: ${{ secrets.MEND_TOKEN }} WS_PRODUCTNAME: Puppet Enterprise WS_PROJECTNAME: ${{ github.event.repository.name }} puppetlabs-clj-shell-utils-f5155d1/.gitignore000066400000000000000000000001071462347712700212410ustar00rootroot00000000000000.lein* pom.xml /target/ /resources/locales.clj /dev-resources/i18n/bin puppetlabs-clj-shell-utils-f5155d1/.travis.yml000066400000000000000000000001341462347712700213620ustar00rootroot00000000000000language: clojure lein: 2.9.1 jdk: - openjdk8 - openjdk11 notifications: email: false puppetlabs-clj-shell-utils-f5155d1/CHANGELOG.md000066400000000000000000000002751462347712700210700ustar00rootroot00000000000000## 2.0.0 * update to clj parent 7.3.15 * add in the i18n plugin, and Makefiles ## 1.0.2 * Built with the same code as 1.0.0, but with java8 instead of java11 ## 1.0.0 * Initial release puppetlabs-clj-shell-utils-f5155d1/CODEOWNERS000066400000000000000000000000271462347712700206450ustar00rootroot00000000000000* @puppetlabs/dumpling puppetlabs-clj-shell-utils-f5155d1/CONTRIBUTING.md000066400000000000000000000010171462347712700215030ustar00rootroot00000000000000# How to contribute Third-party patches are essential for keeping puppet open-source projects great. We want to keep it as easy as possible to contribute changes that allow you to get the most out of our projects. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. For more info, see our canonical guide to contributing: [https://github.com/puppetlabs/puppet/blob/master/CONTRIBUTING.md](https://github.com/puppetlabs/puppet/blob/master/CONTRIBUTING.md) puppetlabs-clj-shell-utils-f5155d1/LICENSE000066400000000000000000000260741462347712700202710ustar00rootroot00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. puppetlabs-clj-shell-utils-f5155d1/Makefile000066400000000000000000000000441462347712700207110ustar00rootroot00000000000000include dev-resources/Makefile.i18n puppetlabs-clj-shell-utils-f5155d1/README.md000066400000000000000000000016031462347712700205320ustar00rootroot00000000000000# puppetlabs/clj-shell-utils A library for shell execution common to Puppet clojure projects. ## Installation Add the following dependency to your `project.clj` file: [![Clojars Project](http://clojars.org/puppetlabs/clj-shell-utils/latest-version.svg)](http://clojars.org/puppetlabs/clj-shell-utils) ## License Copyright © 2019 Puppet Labs See [LICENSE](LICENSE) file. ## Support Please log tickets and issues at our [JIRA tracker](https://tickets.puppetlabs.com/). We use semantic version numbers for our releases, and recommend that users stay as up-to-date as possible by upgrading to patch releases and minor releases as they become available. Bugfixes and ongoing development will occur in minor releases for the current major version. Security fixes will be backported to a previous major version on a best-effort basis, until the previous major version is no longer maintained. puppetlabs-clj-shell-utils-f5155d1/dev-resources/000077500000000000000000000000001462347712700220415ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/dev-resources/Makefile.i18n000066400000000000000000000141321462347712700242600ustar00rootroot00000000000000# -*- Makefile -*- # This file was generated by the i18n leiningen plugin # Do not edit this file; it will be overwritten the next time you run # lein i18n init # # The name of the package into which the translations bundle will be placed BUNDLE=puppetlabs.clj_shell_utils # The name of the POT file into which the gettext code strings (msgid) will be placed POT_NAME=clj-shell-utils.pot # The list of names of packages covered by the translation bundle; # by default it contains a single package - the same where the translations # bundle itself is placed - but this can be overridden - preferably in # the top level Makefile PACKAGES?=$(BUNDLE) LOCALES=$(basename $(notdir $(wildcard locales/*.po))) BUNDLE_DIR=$(subst .,/,$(BUNDLE)) BUNDLE_FILES=$(patsubst %,resources/$(BUNDLE_DIR)/Messages_%.class,$(LOCALES)) FIND_SOURCES=find src -name \*.clj # xgettext before 0.19 does not understand --add-location=file. Even CentOS # 7 ships with an older gettext. We will therefore generate full location # info on those systems, and only file names where xgettext supports it LOC_OPT=$(shell xgettext --add-location=file -f - /dev/null 2>&1 && echo --add-location=file || echo --add-location) LOCALES_CLJ=resources/locales.clj define LOCALES_CLJ_CONTENTS { :locales #{$(patsubst %,"%",$(LOCALES))} :packages [$(patsubst %,"%",$(PACKAGES))] :bundle $(patsubst %,"%",$(BUNDLE).Messages) } endef export LOCALES_CLJ_CONTENTS i18n: msgfmt # Update locales/.pot update-pot: locales/$(POT_NAME) locales/$(POT_NAME): $(shell $(FIND_SOURCES)) | locales @tmp=$$(mktemp $@.tmp.XXXX); \ $(FIND_SOURCES) \ | xgettext --from-code=UTF-8 --language=lisp \ --copyright-holder='Puppet ' \ --package-name="$(BUNDLE)" \ --package-version="$(BUNDLE_VERSION)" \ --msgid-bugs-address="docs@puppet.com" \ -k \ -kmark:1 -ki18n/mark:1 \ -ktrs:1 -ki18n/trs:1 \ -ktru:1 -ki18n/tru:1 \ -ktrun:1,2 -ki18n/trun:1,2 \ -ktrsn:1,2 -ki18n/trsn:1,2 \ $(LOC_OPT) \ --add-comments --sort-by-file \ -o $$tmp -f -; \ sed -i.bak -e 's/charset=CHARSET/charset=UTF-8/' $$tmp; \ sed -i.bak -e 's/POT-Creation-Date: [^\\]*/POT-Creation-Date: /' $$tmp; \ rm -f $$tmp.bak; \ if ! diff -q -I POT-Creation-Date $$tmp $@ >/dev/null 2>&1; then \ mv $$tmp $@; \ else \ rm $$tmp; touch $@; \ fi # Run msgfmt over all .po files to generate Java resource bundles # and create the locales.clj file msgfmt: $(BUNDLE_FILES) $(LOCALES_CLJ) clean-orphaned-bundles # Force rebuild of locales.clj if its contents is not the the desired one. The # shell echo is used to add a trailing newline to match the one from `cat` ifneq ($(shell cat $(LOCALES_CLJ) 2> /dev/null),$(shell echo '$(LOCALES_CLJ_CONTENTS)')) .PHONY: $(LOCALES_CLJ) endif $(LOCALES_CLJ): | resources @echo "Writing $@" @echo "$$LOCALES_CLJ_CONTENTS" > $@ # Remove every resource bundle that wasn't generated from a PO file. # We do this because we used to generate the english bundle directly from the POT. .PHONY: clean-orphaned-bundles clean-orphaned-bundles: @for bundle in resources/$(BUNDLE_DIR)/Messages_*.class; do \ locale=$$(basename "$$bundle" | sed -E -e 's/\$$?1?\.class$$/_class/' | cut -d '_' -f 2;); \ if [ ! -f "locales/$$locale.po" -a -f "$$bundle" ]; then \ rm "$$bundle"; \ fi \ done resources/$(BUNDLE_DIR)/Messages_%.class: locales/%.po | resources msgfmt --java2 -d resources -r $(BUNDLE).Messages -l $(*F) $< # Use this to initialize translations. Updating the PO files is done # automatically through a CI job that utilizes the scripts in the project's # `bin` file, which themselves come from the `clj-i18n` project. locales/%.po: | locales @if [ ! -f $@ ]; then \ touch $@ && msginit --no-translator -l $(*F) -o $@ -i locales/$(POT_NAME); \ fi resources locales: @mkdir $@ help: $(info $(HELP)) @echo .PHONY: help define HELP This Makefile assists in handling i18n related tasks during development. Files that need to be checked into source control are put into the locales/ directory. They are locales/$(POT_NAME) - the POT file generated by 'make update-pot' locales/$$LANG.po - the translations for $$LANG Only the $$LANG.po files should be edited manually; this is usually done by translators. You can use the following targets: i18n: refresh all the files in locales/ and recompile resources update-pot: extract strings and update locales/$(POT_NAME) locales/LANG.po: create translations for LANG msgfmt: compile the translations into Java classes; this step is needed to make translations available to the Clojure code and produces Java class files in resources/ endef # @todo lutter 2015-04-20: for projects that use libraries with their own # translation, we need to combine all their translations into one big po # file and then run msgfmt over that so that we only have to deal with one # resource bundle puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/000077500000000000000000000000001462347712700242205ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/000077500000000000000000000000001462347712700267645ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test/000077500000000000000000000000001462347712700323525ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test/cat000077500000000000000000000000301462347712700330400ustar00rootroot00000000000000#!/usr/bin/env sh cat -puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test/echo000077500000000000000000000000331462347712700332120ustar00rootroot00000000000000#!/usr/bin/env sh echo $@ echo_and_warn000077500000000000000000000000741462347712700350110ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test#!/usr/bin/env sh echo "to out:" $@ echo "to err:" $@ 1>&2 puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test/echo_cwd000077500000000000000000000000351462347712700340510ustar00rootroot00000000000000#!/usr/bin/env sh echo $PWD echo_foo_env_var000077500000000000000000000000351462347712700355200ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test#!/usr/bin/env sh echo $FOO puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test/false000077500000000000000000000000321462347712700333650ustar00rootroot00000000000000#!/usr/bin/env sh exit 1 puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test/gen-output000077500000000000000000000000751462347712700344110ustar00rootroot00000000000000#!/usr/bin/env sh dd if=/dev/zero bs=$1 count=1 2>/dev/null list_env_var_names000077500000000000000000000004201462347712700360730ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test#!/usr/bin/env sh # -s supresses lines that don't have an equals sign in them (this prevents bar in FOO=foo\nbar from being interpretted as a environment key) # -f selects which part of the split line to select # -d specifies the delimiter printenv | cut -s -f 1 -d "=" puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test/num-args000077500000000000000000000000331462347712700340250ustar00rootroot00000000000000#!/usr/bin/env sh exit $# puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test/true000077500000000000000000000000321462347712700332520ustar00rootroot00000000000000#!/usr/bin/env sh exit 0 puppetlabs-clj-shell-utils-f5155d1/dev-resources/puppetlabs/puppetserver/shell_utils_test/warn000077500000000000000000000000401462347712700332410ustar00rootroot00000000000000#!/usr/bin/env sh echo $@ 1>&2 puppetlabs-clj-shell-utils-f5155d1/project.clj000066400000000000000000000024741462347712700214220ustar00rootroot00000000000000(defproject puppetlabs/clj-shell-utils "2.0.0" :description "Clojure shell execution utilities" :min-lein-version "2.9.0" :parent-project {:coords [puppetlabs/clj-parent "7.3.15"] :inherit [:managed-dependencies]} :pedantic? :abort :test-paths ["test/unit"] :plugins [[lein-project-version "0.1.0"] [lein-parent "0.3.6"] [puppetlabs/i18n "0.9.0"]] :source-paths ["src/clj"] :java-source-paths ["src/java"] :dependencies [[org.clojure/clojure] [prismatic/schema] [org.apache.commons/commons-exec] [commons-io] [org.slf4j/log4j-over-slf4j] [org.slf4j/slf4j-api] [puppetlabs/trapperkeeper] [puppetlabs/kitchensink] [puppetlabs/i18n]] :profiles { :test { :dependencies [[puppetlabs/trapperkeeper nil :classifier "test" :scope "test"]]}} :deploy-repositories [["releases" {:url "https://clojars.org/repo" :username :env/clojars_jenkins_username :password :env/clojars_jenkins_password :sign-releases false}] ["snapshots" "http://nexus.delivery.puppetlabs.net/content/repositories/snapshots/"]]) puppetlabs-clj-shell-utils-f5155d1/src/000077500000000000000000000000001462347712700200425ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/src/clj/000077500000000000000000000000001462347712700206125ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/src/clj/puppetlabs/000077500000000000000000000000001462347712700227715ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/src/clj/puppetlabs/puppetserver/000077500000000000000000000000001462347712700255355ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/src/clj/puppetlabs/puppetserver/shell_utils.clj000066400000000000000000000102361462347712700305600ustar00rootroot00000000000000(ns puppetlabs.puppetserver.shell-utils (:require [schema.core :as schema] [clojure.java.io :as io] [puppetlabs.kitchensink.core :as ks] [clojure.string :as string] [puppetlabs.i18n.core :as i18n]) (:import (com.puppetlabs.puppetserver ShellUtils ShellUtils$ExecutionOptions) (java.io InputStream) (org.apache.commons.io IOUtils))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Schemas (def ExecutionResult "A map that contains the details of the result of executing a command." {:exit-code schema/Int :stderr schema/Str :stdout schema/Str}) (def ExecutionResultStreamed "A map that contains the details of the result of executing a command with stdout as a stream." {:exit-code schema/Int :stderr schema/Str :stdout InputStream}) (def ExecutionOptions {(schema/optional-key :args) [schema/Str] (schema/optional-key :env) (schema/maybe {schema/Str schema/Str}) (schema/optional-key :in) (schema/maybe InputStream) (schema/optional-key :cwd) (schema/maybe schema/Str)}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Internal (def default-execution-options {:args [] :env nil :in nil :cwd nil}) (schema/defn ^:always-validate java-exe-options :- ShellUtils$ExecutionOptions [{:keys [env in cwd]} :- ExecutionOptions] (let [exe-options (ShellUtils$ExecutionOptions.)] (.setStdin exe-options in) (when env (.setEnv exe-options (ks/mapkeys name env))) (when cwd (.setWorkingDirectory exe-options cwd)) exe-options)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Public (schema/defn ^:always-validate validate-command! "Checks the command string to ensure that it is an absolute path, executable and that the file exists. An exception is thrown if any of those are not the case." [command :- schema/Str] (let [command-file (io/as-file command)] (cond (not (.isAbsolute command-file)) (throw (IllegalArgumentException. (i18n/trs "An absolute path is required, but ''{0}'' is not an absolute path" command))) (not (.exists command-file)) (let [cmds (string/split command #" ")] (if (and (> (count cmds) 1) (.exists (io/as-file (first cmds)))) (throw (IllegalArgumentException. (i18n/trs "Command ''{0}'' appears to use command-line arguments, but this is not allowed." command))) (throw (IllegalArgumentException. (i18n/trs "The referenced command ''{0}'' does not exist" command))))) (not (.canExecute command-file)) (throw (IllegalArgumentException. (i18n/trs "The referenced command ''{0}'' is not executable" command)))))) (schema/defn ^:always-validate execute-command-streamed :- ExecutionResultStreamed "Execute the specified fully qualified command (string) and any included command-arguments (vector of strings) and return the exit-code (integer), and the contents of the stdout (stream) and stderr (string) for the command." ([command :- schema/Str] (execute-command-streamed command {})) ([command :- schema/Str opts :- ExecutionOptions] (let [{:keys [args] :as opts} (merge default-execution-options opts)] (validate-command! command) (let [process (ShellUtils/executeCommand command (into-array String args) (java-exe-options opts))] {:exit-code (.getExitCode process) :stderr (.getError process) :stdout (.getOutputAsStream process)})))) (schema/defn ^:always-validate execute-command :- ExecutionResult "Execute the specified fully qualified command (string) and any included command-arguments (vector of strings) and return the exit-code (integer), and the contents of the stdout (string) and stderr (string) for the command." ([command :- schema/Str] (execute-command command {})) ([command :- schema/Str opts :- ExecutionOptions] (let [result (execute-command-streamed command opts)] (update-in result [:stdout] (fn [stdout] (IOUtils/toString stdout "UTF-8")))))) puppetlabs-clj-shell-utils-f5155d1/src/java/000077500000000000000000000000001462347712700207635ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/src/java/com/000077500000000000000000000000001462347712700215415ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/src/java/com/puppetlabs/000077500000000000000000000000001462347712700237205ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/src/java/com/puppetlabs/puppetserver/000077500000000000000000000000001462347712700264645ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/src/java/com/puppetlabs/puppetserver/ExecutionResult.java000066400000000000000000000013561462347712700324760ustar00rootroot00000000000000package com.puppetlabs.puppetserver; import java.io.InputStream; import java.io.IOException; import org.apache.commons.io.IOUtils; public class ExecutionResult { private final InputStream output; private final String error; private final int exitCode; public ExecutionResult(InputStream output, String error, int exitCode) { this.output = output; this.error = error; this.exitCode = exitCode; } public int getExitCode() { return exitCode; } public String getOutput() throws IOException { return IOUtils.toString(output, "UTF-8"); } public InputStream getOutputAsStream() { return output; } public String getError() { return error; } } puppetlabs-clj-shell-utils-f5155d1/src/java/com/puppetlabs/puppetserver/ShellUtils.java000066400000000000000000000220321462347712700314160ustar00rootroot00000000000000package com.puppetlabs.puppetserver; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.PumpStreamHandler; import org.apache.commons.exec.CommandLine; import org.apache.commons.io.output.TeeOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.File; import java.util.Map; public class ShellUtils { public static class ExecutionOptions { private boolean combineStdoutStderr = false; private Map env = null; private InputStream stdin = null; private String cwd = null; public boolean getCombineStdoutStderr() { return combineStdoutStderr; } public void setCombineStdoutStderr(boolean combineStdoutStderr) { this.combineStdoutStderr = combineStdoutStderr; } public InputStream getStdin() { return stdin; } public void setStdin(InputStream stdin) { this.stdin = stdin; } public Map getEnv() { return env; } public void setEnv(Map env) { this.env = env; } public String getWorkingDirectory() { return cwd; } public void setWorkingDirectory(String cwd) { this.cwd = cwd; } } private static final Logger log = LoggerFactory.getLogger(ShellUtils.class); /** * Takes a prepared CommandLine instance and executes it using some sane * defaults and a DefaultExecutor. Also makes a delicious pancake. * * @param commandLine CommandLine instance to execute * @param options optional object [ExecutionOptions] to control behavior; may be null. * @return An ExecutionResult with output[String], error[String], and * the exit code[Integer] of the process * * @throws InterruptedException * @throws IOException */ private static ExecutionResult executeExecutor(CommandLine commandLine, ExecutionOptions options) throws InterruptedException, IOException { if (options == null) { options = new ExecutionOptions(); } DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream errStream = new ByteArrayOutputStream(); // TODO the nice thing here would be to set up a piped stream // arrangement like: // PipedOutputStream stdoutOutputStream = new PipedOutputStream(); // PipedInputStream stdoutInputStream = new PipedInputStream(stdoutOutputStream); // but this requires that the input stream be read on a different thread // than this one. this is currently out of scope. ByteArrayOutputStream stdoutOutputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler; if (options.getCombineStdoutStderr()) { log.debug("Combining STDOUT/STDERR for external command '" + commandLine.toString() + "'"); streamHandler = new PumpStreamHandler( stdoutOutputStream, new TeeOutputStream(stdoutOutputStream, errStream), options.getStdin()); } else { streamHandler = new PumpStreamHandler(stdoutOutputStream, errStream, options.getStdin()); } // Don't throw exception on non-zero exit code executor.setExitValues(null); // Set up the handlers executor.setStreamHandler(streamHandler); // Set up cwd String cwd = options.getWorkingDirectory(); if (cwd != null) { executor.setWorkingDirectory(new File(cwd)); } Integer exitCode = executor.execute(commandLine, options.getEnv()); ByteArrayInputStream stdoutInputStream = new ByteArrayInputStream(stdoutOutputStream.toByteArray()); String stdErr = errStream.toString(); if ( ! stdErr.isEmpty() ) { log.warn("Executed an external process which logged to STDERR: " + stdErr); } return new ExecutionResult(stdoutInputStream, stdErr, exitCode); } /** * Executes the given command in a separate process. * * @param commandLine the command to execute. * @param options optional object [ExecutionOptions] to control behavior; may be null. * * @return An ExecutionResult with output[String], error[String], and * the exit code[Integer] of the process * * @throws InterruptedException */ protected static ExecutionResult executeCommand(CommandLine commandLine, ExecutionOptions options) throws InterruptedException { try { return executeExecutor(commandLine, options); } catch (IOException e) { // this nonsense is due to a weird edge-case incompatibility between JDK8 // and apache commons-exec. See SERVER-1116; hopefully we can remove this // conditional once that is resolved. if (e.getMessage() == "Stream closed") { log.warn("An error occurred while executing the command '" + commandLine.getExecutable() + ". The most likely culprit is that you are on JDK8, " + "and we executed an external process with data on its STDIN that was not " + "consumed by the process. Please make sure the command above processes STDIN " + "correctly. For more information, see " + "https://tickets.puppetlabs.com/browse/SERVER-1116 . If you do not believe " + "that this is the root cause of this error message, please file a bug at " + "https://tickets.puppetlabs.com/browse/SERVER."); } throw new IllegalStateException( "Exception while executing '" + commandLine.getExecutable() + "': " + e.getMessage(), e); } } /** * Executes the given command in a separate process. * * @param command the command [String] to execute. arguments can be * included in the string. * @return An ExecutionResult with output[String], error[String], and * the exit code[Integer] of the process * * @throws InterruptedException * @throws IOException */ public static ExecutionResult executeCommand(String command) throws InterruptedException, IOException { CommandLine commandLine = CommandLine.parse(command); return executeCommand(commandLine, null); } /** * Executes the given command in a separate process. * * * @param command the command [String] to execute. arguments can be * included in the string. * @param options optional object [ExecutionOptions] to control behavior; may be null. * @return An ExecutionResult with output[String], error[String], and * the exit code[Integer] of the process * * @throws InterruptedException * @throws IOException */ public static ExecutionResult executeCommand(String command, ExecutionOptions options) throws InterruptedException, IOException { CommandLine commandLine = CommandLine.parse(command); return executeCommand(commandLine, options); } /** * Executes the given command in a separate process. * * @param command the command [String] to execute. * @param arguments arguments [Array of Strings] to add to the command being executed * @return An ExecutionResult with output[String], error[String], and * the exit code[Integer] of the process * * @throws InterruptedException * @throws IOException */ public static ExecutionResult executeCommand(String command, String[] arguments) throws InterruptedException, IOException { return executeCommand(command, arguments, null); } /** * Executes the given command in a separate process. * * @param command the command [String] to execute. * @param arguments arguments [Array of Strings] to add to the command being executed * @param options optional object [ExecutionOptions] to control behavior; may be null. * * @return An ExecutionResult with output[String], error[String], and * the exit code[Integer] of the process * * @throws InterruptedException * @throws IOException */ public static ExecutionResult executeCommand(String command, String[] arguments, ExecutionOptions options) throws InterruptedException, IOException { CommandLine commandLine = new CommandLine(command); commandLine.addArguments(arguments, false); return executeCommand(commandLine, options); } } puppetlabs-clj-shell-utils-f5155d1/test/000077500000000000000000000000001462347712700202325ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/test/unit/000077500000000000000000000000001462347712700212115ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/test/unit/puppetlabs/000077500000000000000000000000001462347712700233705ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/test/unit/puppetlabs/puppetserver/000077500000000000000000000000001462347712700261345ustar00rootroot00000000000000puppetlabs-clj-shell-utils-f5155d1/test/unit/puppetlabs/puppetserver/shell_utils_test.clj000066400000000000000000000140101462347712700322100ustar00rootroot00000000000000(ns puppetlabs.puppetserver.shell-utils-test (:require [clojure.test :refer :all] [puppetlabs.puppetserver.shell-utils :as sh-utils] [puppetlabs.kitchensink.core :as ks] [puppetlabs.trapperkeeper.testutils.logging :as logging] [clojure.string :as str] [clojure.set :as set]) (:import (java.io ByteArrayInputStream) (com.puppetlabs.puppetserver ShellUtils ShellUtils$ExecutionOptions))) (def test-resources (ks/absolute-path "./dev-resources/puppetlabs/puppetserver/shell_utils_test")) (defn script-path [script-name] (str test-resources "/" script-name)) (defn parse-env-output [env-output] (set (str/split-lines env-output))) (deftest returns-the-exit-code (testing "true should return 0" (is (zero? (:exit-code (sh-utils/execute-command (script-path "true")))))) (testing "false should return 1" (is (= 1 (:exit-code (sh-utils/execute-command (script-path "false"))))))) (deftest returns-stdout-correctly (testing "echo should add content to stdout" (is (= "foo\n" (:stdout (sh-utils/execute-command (script-path "echo") {:args ["foo"]})))))) (deftest returns-stderr-correctly (testing "echo can add content to stderr as well" (logging/with-test-logging (is (= "bar\n" (:stderr (sh-utils/execute-command (script-path "warn") {:args ["bar"]}))))))) (deftest combines-stderr-and-stdout-correctly (logging/with-test-logging (let [options (ShellUtils$ExecutionOptions.) _ (.setCombineStdoutStderr options true) results (ShellUtils/executeCommand (str (script-path "echo_and_warn") " baz") options)] (testing "combined info echoed to stdout and stderr captured as output" (let [output (.getOutput results)] ;; Allow stdout and stderr messages to come in either order since ;; the order in which they are read from the different stream ;; consuming threads is not reliable. (is (or (= "to out: baz\nto err: baz\n" output) (= "to err: baz\nto out: baz\n" output)) (format "Output produced, '%s', did not match expected output" output)))) (testing "only info echoed to stderr captured as error" (is (= "to err: baz\n" (.getError results)))) (testing "only stderr info (and not stdout info) is logged" (is (logged? "Executed an external process which logged to STDERR: to err: baz\n" :warn)))))) (deftest pass-args-correctly (testing "passes the expected number of args to cmd" (is (= 5 (:exit-code (sh-utils/execute-command (script-path "num-args") {:args ["a" "b" "c" "d" "e"]})))))) (deftest inherits-env-correctly (testing "inherits environment variables if not specified" (let [env-output (:stdout (sh-utils/execute-command (script-path "list_env_var_names"))) env (parse-env-output env-output)] (is (< 3 (count env)) (str "Expected at least 3 environment variables, got:\n" env-output)) (is (contains? env "PATH")) (is (contains? env "PWD")) (is (contains? env "HOME"))))) (deftest sets-env-correctly (testing "sets environment variables correctly" (is (= "foo\n" (:stdout (sh-utils/execute-command (script-path "echo_foo_env_var") {:env {"FOO" "foo"}})))) (let [env-output (:stdout (sh-utils/execute-command (script-path "list_env_var_names") {:env {"FOO" "foo\nbar"}})) env (parse-env-output env-output) ;; it seems that the JVM always includes a PWD env var, no ;; matter what, and in certain terminals it may also include a few ;; other vars, so we are writing the test to be tolerant of that. expected-keys #{"FOO" "PWD" "_" "SHLVL"} extra-keys (set/difference env expected-keys)] (is (empty? extra-keys) (str "Found unexpected environment variables:" extra-keys))))) (deftest pass-stdin-correctly (testing "passes stdin stream to command" (is (= "foo" (:stdout (sh-utils/execute-command (script-path "cat") {:in (ByteArrayInputStream. (.getBytes "foo" "UTF-8"))})))))) (deftest sets-cwd-correctly (testing "sets current working directory correctly" (let [tmpdir (System/getProperty "java.io.tmpdir")] (is (= (str tmpdir "\n") (:stdout (sh-utils/execute-command (script-path "echo_cwd") {:cwd tmpdir}))))))) (deftest throws-exception-for-non-absolute-path (testing "Commands must be given using absolute paths" (is (thrown? IllegalArgumentException (sh-utils/execute-command "echo"))))) (deftest throws-exception-for-non-existent-file (testing "The given command must exist" (is (thrown-with-msg? IllegalArgumentException #"command '/usr/bin/footest' does not exist" (sh-utils/execute-command "/usr/bin/footest"))))) (deftest throws-reasonable-error-for-arguments-in-command (testing "A meaningful error is raised if arguments are added to the command" (is (thrown-with-msg? IllegalArgumentException #"appears to use command-line arguments, but this is not allowed" (sh-utils/execute-command (str (script-path "echo") " foo")))))) (deftest can-read-more-than-the-pipe-buffer (testing "Doesn't deadlock when reading more than the pipe can hold" (is (= 128000 (count (:stdout (sh-utils/execute-command (script-path "gen-output") {:args ["128000"]})))))))