From dbb8bbf23821127d60482ce296b6af45a4463f9c Mon Sep 17 00:00:00 2001 From: Tom Zhong Date: Wed, 25 Nov 2026 16:10:42 +1030 Subject: [PATCH 1/7] add agent file --- .github/copilot-instructions.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .github/copilot-instructions.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..1136e86 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,30 @@ +# pshell + +SFTP-like command line client for Mediaflux and S3 (Pawsey). Python >= 3.6, standard library only except `boto3` (optional; needed only for S3). + +## Build, test, run + +- Run: `python3 pshell.py [-c config] [-v 0|1|2] [-i script] [-o failed_script] [-u url -t mflux|s3] ["cmd1 && cmd2"]` +- All tests: `./test_all` (runs the four `test_*.py` files with `python3`) +- Single module: `python3 test_parser.py` (also `test_mfclient.py`, `test_s3client.py`, `test_pshell.py`) +- Tests are plain `unittest` with a custom `__main__` that builds the suite from a `test_class_list`. Single method: `python3 -m unittest test_s3client.s3client_standard.test_convert` — except `test_s3client.py`/`test_mfclient.py`, whose `setUp` uses a client global created in `__main__` (and `test_pshell.py`, which uses `config`, `python`, `script`, `verbosity` globals); for those, edit `test_class_list` and run as a script. +- `test_mfclient.py` / `test_s3client.py` use dummy clients (no server needed); `test_pshell.py` runs `pshell.py` as a subprocess and checks exit codes. +- No linter configured. CI (`bitbucket-pipelines.yml`) only runs `python test_mfclient.py` on python:3.6. +- Packaging: `build_test` / `build_release` zip `pshell.py` (as `__main__.py`), `parser.py`, `mfclient.py`, `s3client.py`, `util.py` into an executable zip with a python3 shebang. **Any new module must be added to the file lists in both scripts.** `build_release` rewrites the line starting with `build` in `pshell.py` with a timestamp; keep that line shape. +- `v3/` is a legacy/experimental tree (FUSE mount, older mfclient); `keystone.py` is a standalone helper. Main code is at the repo root. + +## Architecture + +- `pshell.py` – entry point only: argparse, logging, loads `~/.pshell_config` (falls back to `./.pshell_config`), builds endpoints, configures readline, then either runs `parser.loop_interactively()` or feeds `-i` script lines / `&&`-split command-line text to `onecmd()`. Non-interactive failures `sys.exit(-1)`; tests depend on those exit codes. +- `parser.py` – `parser(cmd.Cmd)` holds all user commands (`do_*`), tab completion (`complete_*` delegating to `remote_complete`), the unified get/put progress reporter, a thread pool (`thread_max`), and the `remotes` dict (name → client) with `remotes_current` and `cwd`. Unknown commands fall through `default()` to the active remote's `command()` passthrough; failure raises `SyntaxError`. +- `mfclient.py` (`mf_client`) and `s3client.py` (`s3_client`) are interchangeable backends. `parser.remote_add` picks one by endpoint `type` (`mflux` / `s3`) via `from_endpoint()`, and `endpoint()` serialises it back to config. The parser calls the same method set on both (`cd`, `ls_iter`, `get`, `put`, `rm`, `mkdir`, `rmdir`, `publish`, `info_iter`, `complete_path`, `command`, `login`, `status`...). When adding a command, implement it in both clients (or fail gracefully in one) and add `do_*`/`complete_*` in `parser.py`. +- `util.py` – config file normalisation and endpoint URL helpers. +- Config: INI file with a section per config name (default `pawsey`); `endpoints` is a JSON dict of remote name → `{type, url, ...}`, plus `remotes_current` and `remotes_home`. First-run `pawsey` defaults are hard-coded in `pshell.py`. +- `parser.precmd` blocks commands when the active remote isn't authenticated, except those in the `local_commands` allowlist in `requires_auth`; update it when adding a command that doesn't need a server. + +## Conventions + +- Procedural style; comments are `# ...` at column 0 above the block they describe, and `# ---` separates methods in `parser.py`. +- Remote paths are always `/`-separated; for S3, `path_convert()` maps `/bucket/prefix/key`, and a trailing `/` marks a prefix rather than a key. +- `boto3` is imported in a guarded block in `s3client.py` so Mediaflux-only use works without it; don't add other non-stdlib dependencies. +- Bump `version` in `pshell.py` for releases. From 6458e183d8cc8341ea922a48fbf44747352317cb Mon Sep 17 00:00:00 2001 From: Tom Zhong Date: Wed, 25 Nov 2026 18:14:27 +1030 Subject: [PATCH 2/7] bundle boto3 into the release file --- INSTALL | 16 +++--- build_release | 49 ++++++++-------- mfclient.py | 2 +- parser.py | 2 +- release_main.py | 45 +++++++++++++++ requirements.txt | 1 - s3client.py | 11 +++- test_mfclient.py | 12 ++++ test_release.py | 142 +++++++++++++++++++++++++++++++++++++++++++++++ test_s3client.py | 10 ++++ 10 files changed, 256 insertions(+), 34 deletions(-) create mode 100644 release_main.py create mode 100644 test_release.py diff --git a/INSTALL b/INSTALL index 47c8c06..579031f 100644 --- a/INSTALL +++ b/INSTALL @@ -1,15 +1,17 @@ ### Current -Just use build_release -> zip source bundle and require users to install >= python 3.6 on whatever platform they're on +Run `./build_release` to create the single-file `release/pshell` executable. +It bundles boto3 and its dependencies; users do not need to install them. +It requires Python 3 and extracts its contents to a private temporary directory +while running, which is removed on normal exit. -Users will separately have to install boto3 if they want the S3 functionality. +The build includes separate dependency sets for Python 3.6-3.12 and Python +3.13 or later. Build on a platform compatible with the target system and its +Python runtime. -Can't bundle boto3 in a python zip: https://github.com/boto/boto3/issues/1770 - -This should then work: - -python3 pshell +Run it with `./release/pshell`. +After building, run `python3 test_release.py` to check the packaged executable. ### Docker diff --git a/build_release b/build_release index b5b7c12..69ddd77 100755 --- a/build_release +++ b/build_release @@ -1,32 +1,37 @@ #!/bin/bash +set -e + echo "Building a zip bundle with version timestamp for release" -# setup build dir +# stage the application and its dependencies outside the release directory mkdir -p release -rm release/* -cp pshell.py release/__main__.py -cp parser.py release/parser.py -cp mfclient.py release/mfclient.py -cp s3client.py release/s3client.py -cp util.py release/util.py -cd release +build_dir=$(mktemp -d) +trap 'rm -rf "$build_dir"' EXIT + +cp release_main.py "$build_dir/__main__.py" +cp pshell.py "$build_dir/pshell.py" +cp parser.py mfclient.py s3client.py util.py "$build_dir/" # stamp this release d=$(date +%Y%m%d%H%M%S) -sed -i tmp -e 's/^build.*$/build="'$d'"/' __main__.py +sed 's/^build.*$/build="'$d'"/' "$build_dir/pshell.py" > "$build_dir/pshell.stamped.py" +mv "$build_dir/pshell.stamped.py" "$build_dir/pshell.py" -# build -zip pshell.zip __main__.py parser.py mfclient.py s3client.py util.py -echo "#!/usr/bin/env python3" > pshell -cat pshell.zip >> pshell -chmod u+x pshell +# Include compatible dependency sets for Python 3.6-3.12 and Python 3.13+. +python3 -m pip install --disable-pip-version-check --no-compile \ + --python-version 3.6 --only-binary=:all: \ + --requirement requirements.txt --target "$build_dir/vendor/legacy" +python3 -m pip install --disable-pip-version-check --no-compile \ + --python-version 3.13 --only-binary=:all: \ + --requirement requirements.txt --target "$build_dir/vendor/modern" -# cleanup -rm pshell.zip -rm __main__.py -rm parser.py -rm mfclient.py -rm s3client.py -rm util.py -rm *.pytmp +# build +bundle=$(pwd)/release/pshell.zip +(cd "$build_dir" && zip -qr "$bundle" .) +{ + echo "#!/usr/bin/env python3" + cat "$bundle" +} > release/pshell +chmod u+x release/pshell +rm "$bundle" diff --git a/mfclient.py b/mfclient.py index 40aacb0..c0afec5 100644 --- a/mfclient.py +++ b/mfclient.py @@ -240,7 +240,7 @@ def login(self, user=None, password=None, domain=None, token=None): try: elem = reply.find(".//session") self.session = elem.text - self.logging.info("Established session: %s" % self.session) + self.logging.info("Established session") # refresh connection info self.connect() except Exception as e: diff --git a/parser.py b/parser.py index 5ec08e2..82851d7 100644 --- a/parser.py +++ b/parser.py @@ -153,7 +153,7 @@ def remotes_config_save(self): def remote_add(self, name, endpoint): try: client = None - self.logging.debug("remote: [%s] endpoint: %r" % (name, endpoint)) + self.logging.debug("remote: [%s] endpoint type: [%s]" % (name, endpoint.get('type'))) # create client if endpoint['type'] == 'mflux': client = mfclient.mf_client.from_endpoint(endpoint) diff --git a/release_main.py b/release_main.py new file mode 100644 index 0000000..3b32168 --- /dev/null +++ b/release_main.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 + +import os +import stat +import subprocess +import sys +import tempfile +import zipfile + + +def main(): + try: + with tempfile.TemporaryDirectory(prefix="pshell-") as directory: + with zipfile.ZipFile(sys.argv[0]) as archive: + for entry in archive.infolist(): + parts = entry.filename.split("/") + if (entry.filename.startswith("/") or "\\" in entry.filename + or ".." in parts or stat.S_ISLNK(entry.external_attr >> 16)): + raise ValueError("unsafe archive entry: %s" % entry.filename) + archive.extractall(directory) + + dependency_set = "modern" if sys.version_info >= (3, 13) else "legacy" + environment = os.environ.copy() + dependency_path = os.path.join(directory, "vendor", dependency_set) + if environment.get("PYTHONPATH"): + dependency_path += os.pathsep + environment["PYTHONPATH"] + environment["PYTHONPATH"] = dependency_path + process = subprocess.Popen( + [sys.executable, os.path.join(directory, "pshell.py")] + sys.argv[1:], + env=environment, + ) + try: + returncode = process.wait() + except KeyboardInterrupt: + returncode = process.wait() + if returncode < 0: + return 128 - returncode + return returncode + except (OSError, ValueError, zipfile.BadZipFile) as error: + print("Unable to start bundled pshell: %s" % error, file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/requirements.txt b/requirements.txt index 71e8c88..30ddf82 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1 @@ -bash boto3 diff --git a/s3client.py b/s3client.py index 70484bf..a33e4cb 100644 --- a/s3client.py +++ b/s3client.py @@ -23,8 +23,10 @@ import botocore logging.getLogger('boto3').setLevel(logging.WARNING) logging.getLogger('botocore').setLevel(logging.WARNING) + dependency_error = None ok=True -except: +except Exception as e: + dependency_error = e ok=False #------------------------------------------------------------ @@ -143,7 +145,12 @@ def from_endpoint(cls, endpoint): #------------------------------------------------------------ def connect(self): - self.logging.info('endpoint=%s using acess=%s' % (self.url, self.access)) + self.logging.info('endpoint=%s' % self.url) + + if not self.ok: + self.status = "S3 dependencies unavailable" + self.logging.error("S3 dependencies unavailable: %s", dependency_error) + return False # connection check emsg = "unknown error" diff --git a/test_mfclient.py b/test_mfclient.py index 9ed6283..21e30c4 100755 --- a/test_mfclient.py +++ b/test_mfclient.py @@ -9,6 +9,8 @@ import urllib.request, urllib.error, urllib.parse import binascii import unittest +from unittest import mock +import xml.etree.ElementTree as ET import mfclient import posixpath import configparser @@ -25,6 +27,16 @@ def setUp(self): global mf_client self.mf_client = mf_client + def test_login_does_not_log_session(self): + response = ET.fromstring("dummy-session") + with mock.patch.object(self.mf_client, "aterm_run", return_value=response): + with mock.patch.object(self.mf_client, "connect"): + with self.assertLogs("mfclient", level="INFO") as logs: + self.mf_client.login(user="dummy", password="dummy", domain="dummy") + self.assertEqual(self.mf_client.session, "dummy-session") + self.assertNotIn("dummy-session", "\n".join(logs.output)) + self.mf_client.session = "" + # --- helper: remove common XML wrapper def _peel(self, text): diff --git a/test_release.py b/test_release.py new file mode 100644 index 0000000..0469e7c --- /dev/null +++ b/test_release.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 + +import configparser +import glob +import json +import os +import subprocess +import sys +import tempfile +import threading +import unittest +import venv +import zipfile +from http.server import BaseHTTPRequestHandler, HTTPServer + + +ROOT = os.path.dirname(os.path.abspath(__file__)) +RELEASE = os.path.join(ROOT, "release", "pshell") + + +class S3Handler(BaseHTTPRequestHandler): + def do_GET(self): + self.server.authorizations.append(self.headers.get("Authorization", "")) + self.server.ca_available.append(bool(glob.glob( + os.path.join(self.server.temp_root, "pshell-*", "vendor", "*", + "botocore", "cacert.pem") + ))) + body = (b'' + b'' + b'example-bucket' + b'2020-01-01T00:00:00.000Z' + b'') + self.send_response(200) + self.send_header("Content-Type", "application/xml") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format, *args): + pass + + +class ReleaseTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not os.path.isfile(RELEASE): + raise RuntimeError("Run ./build_release before test_release.py") + cls.temp = tempfile.TemporaryDirectory() + cls.root = cls.temp.name + cls.home = os.path.join(cls.root, "home") + cls.runtime_temp = os.path.join(cls.root, "tmp") + os.mkdir(cls.home) + os.mkdir(cls.runtime_temp) + environment = os.path.join(cls.root, "venv") + venv.create(environment, with_pip=False) + cls.python = os.path.join(environment, "Scripts" if os.name == "nt" else "bin", + "python.exe" if os.name == "nt" else "python") + cls.server = HTTPServer(("127.0.0.1", 0), S3Handler) + cls.server.authorizations = [] + cls.server.ca_available = [] + cls.server.temp_root = cls.runtime_temp + cls.thread = threading.Thread(target=cls.server.serve_forever) + cls.thread.daemon = True + cls.thread.start() + config = configparser.ConfigParser() + config["pawsey"] = { + "endpoints": json.dumps({ + "private": { + "type": "s3", "url": "http://127.0.0.1:%d" % cls.server.server_port, + "access": "dummy-access", "secret": "dummy-secret", + }, + "mediaflux": { + "type": "mflux", "url": "https://example.invalid:443", + "session": "dummy-session", "token": "dummy-token", + }, + }), + "remotes_current": "private", + "remotes_home": "/", + } + with open(os.path.join(cls.home, ".pshell_config"), "w") as config_file: + config.write(config_file) + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.thread.join() + cls.server.server_close() + cls.temp.cleanup() + + def run_release(self, path, *args): + env = {key: value for key, value in os.environ.items() + if not key.startswith("AWS_") and key not in ( + "PYTHONPATH", "PYTHONHOME", "HTTP_PROXY", "HTTPS_PROXY", + "http_proxy", "https_proxy", + )} + env.update({"HOME": self.home, "TMPDIR": self.runtime_temp, + "TEMP": self.runtime_temp, "TMP": self.runtime_temp, + "AWS_EC2_METADATA_DISABLED": "true", "PYTHONNOUSERSITE": "1"}) + return subprocess.run([self.python, path] + list(args), env=env, cwd=self.home, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + universal_newlines=True, timeout=60) + + def test_s3_request_without_installed_dependencies(self): + dependency = subprocess.run([self.python, "-I", "-c", "import boto3"], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + self.assertNotEqual(dependency.returncode, 0, + "Test environment must not have boto3 installed") + result = self.run_release(RELEASE, "-v", "2", "ls") + self.assertEqual(result.returncode, 0, result.stdout) + self.assertIn("example-bucket", result.stdout) + self.assertNotIn("Unable to load data", result.stdout) + for credential in ("dummy-access", "dummy-secret", "dummy-session", "dummy-token"): + self.assertNotIn(credential, result.stdout) + self.assertTrue(self.server.authorizations) + self.assertTrue(all(header.startswith("AWS4-HMAC-SHA256") + for header in self.server.authorizations)) + self.assertTrue(all(self.server.ca_available)) + self.assertEqual(os.listdir(self.runtime_temp), []) + + def test_arguments_and_exit_status(self): + version = self.run_release(RELEASE, "--version") + self.assertEqual(version.returncode, 0, version.stdout) + self.assertIn("pshell version", version.stdout) + invalid = self.run_release(RELEASE, "--invalid-option") + self.assertNotEqual(invalid.returncode, 0) + self.assertIn("unrecognized arguments", invalid.stdout) + self.assertEqual(os.listdir(self.runtime_temp), []) + + def test_rejects_unsafe_archive_entry(self): + bundle = os.path.join(self.root, "unsafe.zip") + with zipfile.ZipFile(bundle, "w") as archive: + archive.write(os.path.join(ROOT, "release_main.py"), "__main__.py") + archive.writestr("../escaped", "invalid") + result = self.run_release(bundle) + self.assertNotEqual(result.returncode, 0) + self.assertIn("unsafe archive entry", result.stdout) + self.assertFalse(os.path.exists(os.path.join(self.runtime_temp, "escaped"))) + self.assertEqual(os.listdir(self.runtime_temp), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/test_s3client.py b/test_s3client.py index 8ea501b..8253566 100755 --- a/test_s3client.py +++ b/test_s3client.py @@ -4,6 +4,7 @@ import hashlib import logging import s3client +from unittest import mock import unittest # global to avoid setup for every test class @@ -16,6 +17,15 @@ def setUp(self): global s3_client self.s3_client = s3_client + def test_missing_dependency_reports_import_error(self): + client = s3client.s3_client(url="https://example.invalid") + client.ok = False + with mock.patch.object(s3client, "dependency_error", ImportError("incompatible boto3")): + with self.assertLogs("s3client", level="ERROR") as logs: + self.assertFalse(client.connect()) + self.assertEqual(client.status, "S3 dependencies unavailable") + self.assertIn("incompatible boto3", logs.output[0]) + # path to bucket,prefix,key conversion tests def test_convert_missing_bucket(self): reply = self.s3_client.path_convert("/") From 6e29b11313ac8e3d11da61b9f7839d725796d2a1 Mon Sep 17 00:00:00 2001 From: Tom Zhong Date: Thu, 26 Nov 2026 10:52:59 +1030 Subject: [PATCH 3/7] update version number to 1.2.3 and add License and Notice file for licensing requirements --- .github/copilot-instructions.md | 4 +- LICENSE | 190 ++++++++++++++++++++++++++++++++ NOTICE | 16 +++ README.md | 7 +- build_release | 1 + pshell.py | 2 +- setup.py | 4 + test_release.py | 9 ++ 8 files changed, 229 insertions(+), 4 deletions(-) create mode 100644 LICENSE create mode 100644 NOTICE diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 1136e86..4456592 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -10,7 +10,7 @@ SFTP-like command line client for Mediaflux and S3 (Pawsey). Python >= 3.6, stan - Tests are plain `unittest` with a custom `__main__` that builds the suite from a `test_class_list`. Single method: `python3 -m unittest test_s3client.s3client_standard.test_convert` — except `test_s3client.py`/`test_mfclient.py`, whose `setUp` uses a client global created in `__main__` (and `test_pshell.py`, which uses `config`, `python`, `script`, `verbosity` globals); for those, edit `test_class_list` and run as a script. - `test_mfclient.py` / `test_s3client.py` use dummy clients (no server needed); `test_pshell.py` runs `pshell.py` as a subprocess and checks exit codes. - No linter configured. CI (`bitbucket-pipelines.yml`) only runs `python test_mfclient.py` on python:3.6. -- Packaging: `build_test` / `build_release` zip `pshell.py` (as `__main__.py`), `parser.py`, `mfclient.py`, `s3client.py`, `util.py` into an executable zip with a python3 shebang. **Any new module must be added to the file lists in both scripts.** `build_release` rewrites the line starting with `build` in `pshell.py` with a timestamp; keep that line shape. +- Packaging: `build_test` / `build_release` zip `pshell.py` (as `__main__.py`), `parser.py`, `mfclient.py`, `s3client.py`, `util.py` into an executable zip with a python3 shebang. **Any new module must be added to the file lists in both scripts.** `build_release` rewrites the line starting with `build` in `pshell.py` with a timestamp; keep that line shape. Release builds also bundle `LICENSE`, `NOTICE`, and the dependency metadata from both vendor sets. - `v3/` is a legacy/experimental tree (FUSE mount, older mfclient); `keystone.py` is a standalone helper. Main code is at the repo root. ## Architecture @@ -26,5 +26,5 @@ SFTP-like command line client for Mediaflux and S3 (Pawsey). Python >= 3.6, stan - Procedural style; comments are `# ...` at column 0 above the block they describe, and `# ---` separates methods in `parser.py`. - Remote paths are always `/`-separated; for S3, `path_convert()` maps `/bucket/prefix/key`, and a trailing `/` marks a prefix rather than a key. -- `boto3` is imported in a guarded block in `s3client.py` so Mediaflux-only use works without it; don't add other non-stdlib dependencies. +- `boto3` is imported in a guarded block in `s3client.py`; release builds bundle it for S3 support, while source runs require it to be installed. don't add other non-stdlib dependencies. - Bump `version` in `pshell.py` for releases. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4dfae5e --- /dev/null +++ b/LICENSE @@ -0,0 +1,190 @@ + Apache 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. + + 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. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..12cbc55 --- /dev/null +++ b/NOTICE @@ -0,0 +1,16 @@ +pshell +Copyright 2026 Pawsey Supercomputing Research Centre + +The project was originally created and maintained by Sean Fleming. + +Third-party components +---------------------- + +Release builds of pshell bundle boto3 and its transitive dependencies, +including botocore, jmespath, s3transfer, python-dateutil, urllib3, and +certifi. These components are provided under their respective upstream +licenses. License and package metadata are included in the vendor directories +inside the pshell executable archive. + +"AWS", "Amazon Web Services", "boto3", "botocore", and "S3" are names or +trademarks of Amazon Web Services or its affiliates. diff --git a/README.md b/README.md index 43ef4bf..f0c657e 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,8 @@ Install python >= 3.6 on the platform of your choice. Invoke pshell.py or the prepackaged binary distribution. -Note that you will need to install (eg via pip3) boto3 if you want to use the S3 capabilities. +Release builds bundle boto3 and its dependencies for S3 support. Source runs +require a compatible boto3 installation. ### How do I run the tests? ### @@ -26,3 +27,7 @@ Features: - SFTP-like syntax - Tab completion - Basic support for passthru commands + +## License + +pshell is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE). diff --git a/build_release b/build_release index 69ddd77..8339202 100755 --- a/build_release +++ b/build_release @@ -11,6 +11,7 @@ trap 'rm -rf "$build_dir"' EXIT cp release_main.py "$build_dir/__main__.py" cp pshell.py "$build_dir/pshell.py" cp parser.py mfclient.py s3client.py util.py "$build_dir/" +cp LICENSE NOTICE "$build_dir/" # stamp this release d=$(date +%Y%m%d%H%M%S) diff --git a/pshell.py b/pshell.py index fa2aa5c..22b2b1d 100755 --- a/pshell.py +++ b/pshell.py @@ -27,7 +27,7 @@ # auto build="repository" -version="v1.2.2" +version="v1.2.3" #------------------------------------------------------------ def main(): diff --git a/setup.py b/setup.py index a01c7e4..ce6195b 100644 --- a/setup.py +++ b/setup.py @@ -5,6 +5,10 @@ author='Sean Fleming', author_email='sean.fleming@pawsey.org.au', url='https://bitbucket.org/datapawsey/mfclient', + license='Apache-2.0', + classifiers=[ + 'License :: OSI Approved :: Apache Software License', + ], packages=['data'], py_modules=['pshell','parser', 'mfclient', 's3client', 'util'], ) diff --git a/test_release.py b/test_release.py index 0469e7c..ece2fc6 100644 --- a/test_release.py +++ b/test_release.py @@ -126,6 +126,15 @@ def test_arguments_and_exit_status(self): self.assertIn("unrecognized arguments", invalid.stdout) self.assertEqual(os.listdir(self.runtime_temp), []) + def test_bundles_license_and_notice_files(self): + with zipfile.ZipFile(RELEASE) as archive: + names = set(archive.namelist()) + self.assertIn("LICENSE", names) + self.assertIn("NOTICE", names) + vendor_notices = [name for name in names if ".dist-info/" in name + and ("licenses/" in name or name.endswith("/METADATA"))] + self.assertTrue(vendor_notices) + def test_rejects_unsafe_archive_entry(self): bundle = os.path.join(self.root, "unsafe.zip") with zipfile.ZipFile(bundle, "w") as archive: From 7218bbec486ef177364bf2aa5fc45421caca3029 Mon Sep 17 00:00:00 2001 From: Tom Zhong Date: Thu, 26 Nov 2026 12:34:58 +1030 Subject: [PATCH 4/7] add ci.yml file --- .github/workflows/ci.yml | 41 ++++++++++++++++++++++++++++++++++++++++ build_test | 30 +++-------------------------- 2 files changed, 44 insertions(+), 27 deletions(-) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..610bed9 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + +jobs: + test: + name: Python ${{ matrix.python-version }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: + - "3.9" + - "3.12" + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: pip + + - name: Install dependencies + run: python -m pip install --upgrade pip && python -m pip install -r requirements.txt + + - name: Run test suite + run: ./test_all + + - name: Build executable bundle + run: ./build_test + + - name: Test executable bundle + run: python test_release.py diff --git a/build_test b/build_test index d438dc9..d485f10 100755 --- a/build_test +++ b/build_test @@ -1,30 +1,6 @@ #!/bin/bash -echo "Build a zip bundle for testing - use build_release for artifact publishing" +set -e -# setup build dir -mkdir -p tester -cp pshell.py tester/__main__.py -cp parser.py tester/parser.py -cp mfclient.py tester/mfclient.py -cp s3client.py tester/s3client.py -cp util.py tester/util.py -cd tester - -# build -zip pshell.zip __main__.py parser.py mfclient.py s3client.py util.py -echo "#!/usr/bin/env python3" > pshell -cat pshell.zip >> pshell -chmod u+x pshell -cp pshell .. - -# cleanup -rm pshell.zip -rm __main__.py -rm parser.py -rm mfclient.py -rm s3client.py -rm util.py -rm -rf *.pytmp -cd .. -rm -rf tester +echo "Building a zip bundle for testing - use build_release for artifact publishing" +./build_release From 7c12bb360c4cee43a7cf5b747635da7edb559a19 Mon Sep 17 00:00:00 2001 From: Tom Zhong Date: Thu, 26 Nov 2026 17:18:48 +1030 Subject: [PATCH 5/7] update ci file to test under python3.6 --- .github/copilot-instructions.md | 8 ++--- .github/workflows/ci.yml | 27 ++++++++++++++++- test_all | 13 +++++--- test_mfclient.py | 11 +++++-- test_parser.py | 3 +- test_pshell.py | 2 +- test_runner.py | 54 +++++++++++++++++++++++++++++++++ test_s3client.py | 3 +- 8 files changed, 107 insertions(+), 14 deletions(-) create mode 100644 test_runner.py diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 4456592..c6d9de9 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -5,12 +5,12 @@ SFTP-like command line client for Mediaflux and S3 (Pawsey). Python >= 3.6, stan ## Build, test, run - Run: `python3 pshell.py [-c config] [-v 0|1|2] [-i script] [-o failed_script] [-u url -t mflux|s3] ["cmd1 && cmd2"]` -- All tests: `./test_all` (runs the four `test_*.py` files with `python3`) +- All tests: `./test_all` (runs the four main test modules and `test_runner.py` with `python3`; release bundle tests are separate) - Single module: `python3 test_parser.py` (also `test_mfclient.py`, `test_s3client.py`, `test_pshell.py`) -- Tests are plain `unittest` with a custom `__main__` that builds the suite from a `test_class_list`. Single method: `python3 -m unittest test_s3client.s3client_standard.test_convert` — except `test_s3client.py`/`test_mfclient.py`, whose `setUp` uses a client global created in `__main__` (and `test_pshell.py`, which uses `config`, `python`, `script`, `verbosity` globals); for those, edit `test_class_list` and run as a script. +- The four main test modules use `unittest` with a custom `__main__` that builds the suite from a `test_class_list`. Single method: `python3 -m unittest test_s3client.s3client_standard.test_convert` — except `test_s3client.py`/`test_mfclient.py`, whose `setUp` uses a client global created in `__main__` (and `test_pshell.py`, which uses `config`, `python`, `script`, `verbosity` globals); for those, edit `test_class_list` and run as a script. - `test_mfclient.py` / `test_s3client.py` use dummy clients (no server needed); `test_pshell.py` runs `pshell.py` as a subprocess and checks exit codes. -- No linter configured. CI (`bitbucket-pipelines.yml`) only runs `python test_mfclient.py` on python:3.6. -- Packaging: `build_test` / `build_release` zip `pshell.py` (as `__main__.py`), `parser.py`, `mfclient.py`, `s3client.py`, `util.py` into an executable zip with a python3 shebang. **Any new module must be added to the file lists in both scripts.** `build_release` rewrites the line starting with `build` in `pshell.py` with a timestamp; keep that line shape. Release builds also bundle `LICENSE`, `NOTICE`, and the dependency metadata from both vendor sets. +- No linter configured. GitHub Actions runs the full suite and release bundle tests on Python 3.9, 3.12 and 3.6 (in a container). The older Bitbucket pipeline only runs `python test_mfclient.py` on python:3.6. +- Packaging: `build_test` calls `build_release`, which uses `release_main.py` as `__main__.py` and bundles `pshell.py`, `parser.py`, `mfclient.py`, `s3client.py`, `util.py`, `LICENSE`, `NOTICE`, and both dependency sets into an executable zip. Add new application modules to the file list in `build_release`. The release script stamps the `build` line in its staged copy of `pshell.py`. - `v3/` is a legacy/experimental tree (FUSE mount, older mfclient); `keystone.py` is a standalone helper. Main code is at the repo root. ## Architecture diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 610bed9..0539a29 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ permissions: jobs: test: name: Python ${{ matrix.python-version }} - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: @@ -39,3 +39,28 @@ jobs: - name: Test executable bundle run: python test_release.py + + test-python-36: + name: Python 3.6 + runs-on: ubuntu-24.04 + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python for building + uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + + - name: Build executable bundle + run: ./build_test + + - name: Run tests with Python 3.6 + run: | + docker run --rm \ + --volume "$GITHUB_WORKSPACE:/workspace" \ + --workdir /workspace \ + python:3.6.15-bullseye \ + bash -ec 'python -m pip install -r requirements.txt && ./test_all && python test_release.py' diff --git a/test_all b/test_all index 23b965f..a7a7b3e 100755 --- a/test_all +++ b/test_all @@ -1,4 +1,9 @@ -python3 test_pshell.py -python3 test_parser.py -python3 test_mfclient.py -python3 test_s3client.py +#!/bin/sh + +status=0 +python3 test_pshell.py || status=1 +python3 test_parser.py || status=1 +python3 test_mfclient.py || status=1 +python3 test_s3client.py || status=1 +python3 test_runner.py || status=1 +exit "$status" diff --git a/test_mfclient.py b/test_mfclient.py index 21e30c4..698bc7e 100755 --- a/test_mfclient.py +++ b/test_mfclient.py @@ -78,7 +78,14 @@ def test_empty_property_value(self): def test_service_add(self): line = 'system.service.add :name custom.service :replace-if-exists true :access ACCESS :definition < :element -name arg1 -type string :element -name arg2 -type string -min-occurs 0 -default " " :element -name arg3 -type boolean -min-occurs 0 -default false > :execute \"return [xvalue result [asset.script.execute :id 1 :arg -name namespace [xvalue namespace $args] :arg -name page [xvalue page $args] :arg -name recurse [xvalue recurse $args]]]\"' reply = self.mf_client.aterm_run(line, post=False) - self.assertEqual(self._peel(reply), 'custom.servicetrueACCESSreturn [xvalue result [asset.script.execute :id 1 :arg -name namespace [xvalue namespace $args] :arg -name page [xvalue page $args] :arg -name recurse [xvalue recurse $args]]]') + expected = 'custom.servicetrueACCESSreturn [xvalue result [asset.script.execute :id 1 :arg -name namespace [xvalue namespace $args] :arg -name page [xvalue page $args] :arg -name recurse [xvalue recurse $args]]]' + + def xml_structure(element): + return (element.tag, element.attrib, element.text, element.tail, + [xml_structure(child) for child in element]) + + self.assertEqual(xml_structure(ET.fromstring(self._peel(reply))), + xml_structure(ET.fromstring(expected))) def test_semicolon_value(self): line = 'actor.grant :name public:public :type user :role -type role read-only' @@ -239,5 +246,5 @@ def test_copy_file(self): suite = unittest.TestSuite(suite_list) # run suite - unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(not unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()) diff --git a/test_parser.py b/test_parser.py index 5040537..82bd408 100755 --- a/test_parser.py +++ b/test_parser.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import parser +import sys import unittest # global to avoid setup for every test class @@ -69,5 +70,5 @@ def test_abspath_prefix_resolve(self): suite = unittest.TestSuite(suite_list) # run suite - unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(not unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()) diff --git a/test_pshell.py b/test_pshell.py index 1b28bb6..198ba42 100755 --- a/test_pshell.py +++ b/test_pshell.py @@ -108,5 +108,5 @@ def test_lls(self): suite = unittest.TestSuite(suite_list) # run suite - unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(not unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()) diff --git a/test_runner.py b/test_runner.py new file mode 100644 index 0000000..12bf3bf --- /dev/null +++ b/test_runner.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 + +import os +import subprocess +import sys +import tempfile +import unittest + + +ROOT = os.path.dirname(os.path.abspath(__file__)) +TEST_SCRIPTS = ("test_pshell.py", "test_parser.py", "test_mfclient.py", + "test_s3client.py", "test_runner.py") + + +class TestRunnerStatus(unittest.TestCase): + def test_test_scripts_return_failure(self): + code = ( + 'import runpy, unittest; ' + 'unittest.TextTestRunner.run = lambda self, suite: ' + 'type("Failed", (), {"wasSuccessful": lambda self: False})(); ' + 'runpy.run_path(%r, run_name="__main__")' + ) + for script in TEST_SCRIPTS[:-1]: + with self.subTest(script=script): + result = subprocess.run( + [sys.executable, "-c", code % script], cwd=ROOT, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertNotIn(b"Traceback", result.stderr) + + def test_test_all_returns_failure_and_runs_all_scripts(self): + with tempfile.TemporaryDirectory() as directory: + python = os.path.join(directory, "python3") + with open(python, "w") as fake: + fake.write('#!/bin/sh\necho "$1" >> "$CALLS"\n' + '[ "$1" != "$FAIL_TEST" ]\n') + os.chmod(python, 0o755) + calls = os.path.join(directory, "calls") + environment = os.environ.copy() + environment["PATH"] = directory + os.pathsep + environment["PATH"] + environment["CALLS"] = calls + for fail in ("", TEST_SCRIPTS[0], TEST_SCRIPTS[-1]): + with self.subTest(fail=fail): + with open(calls, "w"): + pass + environment["FAIL_TEST"] = fail + result = subprocess.run(["./test_all"], cwd=ROOT, env=environment) + self.assertEqual(result.returncode, 1 if fail else 0) + with open(calls) as recorded: + self.assertEqual(recorded.read().splitlines(), list(TEST_SCRIPTS)) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/test_s3client.py b/test_s3client.py index 8253566..44e8307 100755 --- a/test_s3client.py +++ b/test_s3client.py @@ -3,6 +3,7 @@ import json import hashlib import logging +import sys import s3client from unittest import mock import unittest @@ -204,5 +205,5 @@ def test_something(self): suite = unittest.TestSuite(suite_list) # run suite - unittest.TextTestRunner(verbosity=2).run(suite) + sys.exit(not unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()) From 7350de30a446a5de6d02f98c0d901f8f564892a1 Mon Sep 17 00:00:00 2001 From: Tom Zhong Date: Fri, 27 Nov 2026 11:06:37 +1030 Subject: [PATCH 6/7] change test python version to 3.16 (latest) --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0539a29..3069cc9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: matrix: python-version: - "3.9" - - "3.12" + - "3.16" steps: - name: Check out repository From 5ef4d7b014816d3935179827dcee1ef3a6df6c59 Mon Sep 17 00:00:00 2001 From: Tom Zhong Date: Fri, 27 Nov 2026 11:26:43 +1030 Subject: [PATCH 7/7] change the test verstion to python 3.15 --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3069cc9..bcd470f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: matrix: python-version: - "3.9" - - "3.16" + - "3.15" steps: - name: Check out repository