Refactor packages

Signed-off-by: Nikolaos Karaolidis <nick@karaolidis.com>
This commit is contained in:
2025-02-23 23:52:29 +00:00
parent 3360e7f8c3
commit 0ae8128304
108 changed files with 11012 additions and 3025 deletions

View File

@@ -1,8 +0,0 @@
{
user ? throw "user argument is required",
home ? throw "home argument is required",
}:
{ pkgs, ... }:
{
home-manager.users.${user}.home.packages = [ (pkgs.callPackage ./package.nix { }) ];
}

View File

@@ -1,22 +0,0 @@
{ pkgs, ... }:
pkgs.buildGoModule rec {
pname = "jsonify";
version = "0.1.6";
src = fetchGit {
url = "git@github.com:sas-institute-rnd-internal/polaris-jsonify.git";
ref = "main";
rev = "7b8f8a0f0b3c1bbfb7f814c5a3dae5f696ca38e3";
};
vendorHash = "sha256-sJ3Jc7ZC+1s3m5nH6WtXsGVZfLEW7CZAcNtstUpc9M4=";
preBuild = ''
rm -rf sage
'';
installPhase = ''
mkdir -p $out/bin
cp "$GOPATH/bin/polaris-jsonify" $out/bin/jsonify
'';
}

View File

@@ -1,8 +0,0 @@
{
user ? throw "user argument is required",
home ? throw "home argument is required",
}:
{ pkgs, ... }:
{
home-manager.users.${user}.home.packages = [ (pkgs.callPackage ./package.nix { }) ];
}

View File

@@ -1,20 +0,0 @@
{ pkgs, ... }:
pkgs.buildGoModule rec {
pname = "klog";
version = "0.6.2";
src = fetchGit {
url = "git@gitlab.sas.com:convoy/devops/klog.git";
ref = "master";
rev = "17629fe278dd23e12bd6f17ee9db0d2fde37bc6c";
};
vendorHash = "sha256-nYlJhGe1Jd3/ct0XpTdMqbgnnoYM0dqVVVfr9nVsu4o=";
patches = [ ./remove-version-flag.patch ];
preBuild = ''
export GOPROXY="goproxy.unx.sas.com"
export GONOSUMDB="*.sas.com,sassoftware.io"
'';
}

View File

@@ -1,33 +0,0 @@
diff --git a/main.go b/main.go
index 6fee5d3..a8d45dd 100644
--- a/main.go
+++ b/main.go
@@ -5,7 +5,6 @@ import (
"flag"
"fmt"
"os"
- "runtime"
"strings"
"time"
@@ -27,20 +26,8 @@ func main() {
flag.StringVar(&f, "format", "term", "Log output format (one of json|pretty|yaml|line|file|term|logfmt|plain|message|template)")
flag.StringVar(&ml, "l", "trace", "Minimum log level to output (in order, one of trace|debug|info|warn|error|fatal|panic|none|disabled)")
flag.StringVar(&tz, "t", defaultTimeZone, "Timezone to use for formatting log timestamps - One of UTC, Local, or from https://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
- var ver bool
- flag.BoolVar(&ver, "version", false, "Show version information")
flag.Parse()
- if ver {
- fmt.Printf("Copyright © 2021, SAS Institute Inc., Cary, NC, USA. All Rights Reserved.\n"+
- "Command - %s\n"+
- "Version - %s+%s\n"+
- "Build Date - %s\n"+
- "Compiler - %s %s/%s\n",
- "klog", BuildVersion, BuildCommit, BuildDate, runtime.Version(), runtime.GOOS, runtime.GOARCH)
- os.Exit(0)
- }
-
lf, ok := log.Formatters[f]
if !ok {
fmt.Fprintf(os.Stderr, "invalid value for format: [%s] - must be one of json|pretty|yaml|line|file|term|logfmt|plain|message|template", f)

View File

@@ -1,8 +0,0 @@
{
user ? throw "user argument is required",
home ? throw "home argument is required",
}:
{ pkgs, ... }:
{
home-manager.users.${user}.home.packages = [ (pkgs.callPackage ./package.nix { }) ];
}

View File

@@ -1,364 +0,0 @@
diff --git a/.gitignore b/.gitignore
index 07ae204..28e5e8a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,6 +11,8 @@
*.pyo
*.sa
*.so
+*.eggs
+*.__pycache__/
# Logs and databases #
######################
@@ -43,4 +45,4 @@ Thumbs.db
/bin/
build
docker
-/**/.pytest_cache/
\ No newline at end of file
+/**/.pytest_cache/
diff --git a/deployment_report/templates/__init__.py b/deployment_report/templates/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ldap_validator/library/__init__.py b/ldap_validator/library/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/ldap_validator/library/utils/__init__.py b/ldap_validator/library/utils/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/pre_install_report/templates/__init__.py b/pre_install_report/templates/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/setup.cfg b/setup.cfg
index 1c80cb2..4ffdef1 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -2,7 +2,11 @@
name = viya4-ark
author = SAS Institute Inc.
summary = The SAS Viya Administration Resource Kit (SAS Viya ARK) provides tools and utilities to help SAS customers prepare for and gather information about a SAS Viya platform deployment.
-description-file = README.md
-description-content-type = text/markdown
-home-page = https://github.com/sassoftware/viya4-ark
+description_file = README.md
+description_content_type = text/markdown
+home_page = https://github.com/sassoftware/viya4-ark
license = Apache-2.0
+
+[options.entry_points]
+console_scripts =
+ viya4-ark = viya4_ark:main
diff --git a/setup.py b/setup.py
index d3dd4f5..05cbeb7 100644
--- a/setup.py
+++ b/setup.py
@@ -14,10 +14,14 @@
from setuptools import find_packages, setup
+packages = find_packages(exclude=["tests", "*.tests", "*.tests.*", "tests.*"])
+
setup(
- setup_requires=["pbr"],
- pbr=True,
- licenses_files=["LICENSE"],
- packages=find_packages(exclude=["tests", "*.tests", "*.tests.*", "tests.*"]),
+ setup_requires=[],
+ license_files=["LICENSE"],
+ py_modules=["viya4_ark"],
+ packages=packages,
+ include_package_data=True,
+ package_data={package: ["*"] for package in packages},
python_requires=">=3.6",
)
diff --git a/viya-ark.py b/viya-ark.py
deleted file mode 100644
index 7626a89..0000000
--- a/viya-ark.py
+++ /dev/null
@@ -1,139 +0,0 @@
-####################################################################
-# ### viya-ark.py ###
-####################################################################
-# ### Author: SAS Institute Inc. ###
-####################################################################
-# ###
-# Copyright (c) 2020, SAS Institute Inc., Cary, NC, USA. ###
-# All Rights Reserved. ###
-# SPDX-License-Identifier: Apache-2.0 ###
-# ###
-####################################################################
-
-import importlib
-import inspect
-import os
-import pkgutil
-import sys
-
-from viya_ark_library.command import Command
-
-# command line options #
-_HELP_SHORT_OPT_ = "h"
-_HELP_LONG_OPT_ = "help"
-
-# return codes #
-_SUCCESS_RC_ = 0
-_BAD_OPT_RC_ = 1
-
-
-################
-# Main #
-################
-def main(argv: list):
- """
- The main executable method for the viya-ark launcher script.
-
- :param argv: The list of arguments passed at invocation.
- """
- try:
- # get the requested command value #
- command_name = argv[0]
-
- # print the usage and exit, if requested #
- if command_name in (f"-{_HELP_SHORT_OPT_}", f"--{_HELP_LONG_OPT_}"):
- usage(_SUCCESS_RC_)
-
- # convert any dashes in the given command to underscores to align with Pythonic package/module standards #
- command_module_name = command_name.replace("-", "_")
-
- # attempt to import the requested command module #
- imported_module = None
- try:
- imported_module = importlib.import_module(f"{command_module_name}.{command_module_name}")
- except ModuleNotFoundError:
- print()
- print(f"ERROR: Command [{command_name}] not found.")
- usage(_BAD_OPT_RC_)
-
- # find any attributes in the module that implement the Command class using reflection #
- command = None
- for attribute_name in dir(imported_module):
- # get the current module attribute by name #
- attribute = getattr(imported_module, attribute_name)
-
- # if the attribute is: #
- # (1) a class -AND- #
- # (2) a subclass of Command -AND- #
- # (3) not abstract #
- # then the attribute defines a command for the project. #
- if inspect.isclass(attribute) and issubclass(attribute, Command) and not inspect.isabstract(attribute):
- command = attribute
- # the Command implementation was found, the loop can break #
- break
-
- if command is not None:
- # call the Command's run() method to delegate execution to the module, pass all relevant arguments #
- command.run(argv[1:])
- else:
- # if a Command implementation wasn't found, print the usage message #
- print()
- print(f"ERROR: Command [{command_name}] not found.")
- usage(_BAD_OPT_RC_)
-
- except IndexError:
- # if the launcher script wasn't given enough args, print the usage #
- print()
- print("ERROR: A command must be provided.")
- usage(_BAD_OPT_RC_)
-
-
-#################
-# Usage #
-#################
-def usage(exit_code: int):
- """
- Prints the usage statement for the viya-ark launcher script and exits with the provided exit_code.
-
- :param exit_code: The code to return upon exit.
- """
- commands = list()
-
- # walk through all packages parallel to this script #
- paths = [os.path.realpath(os.path.dirname(__file__))]
- for importer, name, is_package in pkgutil.walk_packages(path=paths):
- # skip any objects that are packages (i.e. not modules) #
- if not is_package:
- # import the current module #
- try:
- importlib.import_module(name)
- except ModuleNotFoundError as e:
- # ignore any issues importing pytest, raise any other module import errors
- if e.name != "pytest":
- raise e
-
- for subclass in Command.__subclasses__():
- # create a tuple of command details by calling the command_name() and command_desc() methods #
- command_details = (subclass().command_name(), subclass().command_desc())
- # add the command details to the list of discovered commands #
- commands.append(command_details)
-
- # print the commands as well as the static help command to stdout #
- print()
- print(f"Usage: {os.path.basename(__file__)} <command> [options]")
- print()
- print("Commands:")
- for command in commands:
- print(" {:<30} {}".format(command[0], command[1]))
- help_cmd_display = f"-{_HELP_SHORT_OPT_}, --{_HELP_LONG_OPT_}"
- print(" {:<30} {}".format(help_cmd_display, "Display usage for viya-ark."))
- print()
-
- sys.exit(exit_code)
-
-
-##################
-# __main__ #
-##################
-if __name__ == "__main__":
- main(sys.argv[1:])
diff --git a/viya4_ark.py b/viya4_ark.py
new file mode 100644
index 0000000..1af3b79
--- /dev/null
+++ b/viya4_ark.py
@@ -0,0 +1,136 @@
+####################################################################
+# ### main.py ###
+####################################################################
+# ### Author: SAS Institute Inc. ###
+####################################################################
+# ###
+# Copyright (c) 2020, SAS Institute Inc., Cary, NC, USA. ###
+# All Rights Reserved. ###
+# SPDX-License-Identifier: Apache-2.0 ###
+# ###
+####################################################################
+
+import importlib
+import inspect
+import os
+import pkgutil
+import sys
+
+from viya_ark_library.command import Command
+
+# command line options #
+_HELP_SHORT_OPT_ = "h"
+_HELP_LONG_OPT_ = "help"
+
+# return codes #
+_SUCCESS_RC_ = 0
+_BAD_OPT_RC_ = 1
+
+
+################
+# Main #
+################
+def main():
+ """
+ The main executable method for the viya-ark launcher script.
+ """
+ argv = sys.argv[1:]
+
+ if len(argv) == 0:
+ print("ERROR: A command must be provided.")
+ usage(_BAD_OPT_RC_)
+
+ command_name = argv[0]
+
+ # print the usage and exit, if requested #
+ if command_name in (f"-{_HELP_SHORT_OPT_}", f"--{_HELP_LONG_OPT_}"):
+ usage(_SUCCESS_RC_)
+
+ # convert any dashes in the given command to underscores to align with Pythonic package/module standards #
+ command_module_name = command_name.replace("-", "_")
+
+ # attempt to import the requested command module #
+ imported_module = None
+ try:
+ imported_module = importlib.import_module(f"{command_module_name}.{command_module_name}")
+ except ModuleNotFoundError:
+ print()
+ print(f"ERROR: Command [{command_name}] not found.")
+ usage(_BAD_OPT_RC_)
+
+ # find any attributes in the module that implement the Command class using reflection #
+ command = None
+ for attribute_name in dir(imported_module):
+ # get the current module attribute by name #
+ attribute = getattr(imported_module, attribute_name)
+
+ # if the attribute is: #
+ # (1) a class -AND- #
+ # (2) a subclass of Command -AND- #
+ # (3) not abstract #
+ # then the attribute defines a command for the project. #
+ if inspect.isclass(attribute) and issubclass(attribute, Command) and not inspect.isabstract(attribute):
+ command = attribute
+ # the Command implementation was found, the loop can break #
+ break
+
+ if command is not None:
+ # call the Command's run() method to delegate execution to the module, pass all relevant arguments #
+ command.run(argv[1:])
+ else:
+ # if a Command implementation wasn't found, print the usage message #
+ print()
+ print(f"ERROR: Command [{command_name}] not found.")
+ usage(_BAD_OPT_RC_)
+
+
+#################
+# Usage #
+#################
+def usage(exit_code: int):
+ """
+ Prints the usage statement for the viya-ark launcher script and exits with the provided exit_code.
+
+ :param exit_code: The code to return upon exit.
+ """
+ commands = list()
+
+ # walk through all packages parallel to this script #
+ paths = [os.path.realpath(os.path.dirname(__file__))]
+ for importer, name, is_package in pkgutil.walk_packages(path=paths):
+ # skip any objects that are packages (i.e. not modules) #
+ if is_package:
+ continue
+
+ try:
+ importlib.import_module(name)
+ except ModuleNotFoundError as e:
+ # ignore any issues importing pytest, raise any other module import errors
+ if e.name != "pytest":
+ raise e
+
+ for subclass in Command.__subclasses__():
+ # create a tuple of command details by calling the command_name() and command_desc() methods #
+ command_details = (subclass().command_name(), subclass().command_desc())
+ # add the command details to the list of discovered commands #
+ commands.append(command_details)
+
+ # print the commands as well as the static help command to stdout #
+ print()
+ print(f"Usage: {os.path.basename(__file__)} <command> [options]")
+ print()
+ print("Commands:")
+ for command in commands:
+ print(" {:<30} {}".format(command[0], command[1]))
+ help_cmd_display = f"-{_HELP_SHORT_OPT_}, --{_HELP_LONG_OPT_}"
+ print(" {:<30} {}".format(help_cmd_display, "Display usage for viya-ark."))
+ print()
+
+ sys.exit(exit_code)
+
+
+##################
+# __main__ #
+##################
+if __name__ == "__main__":
+ main()
diff --git a/viya_ark_library/templates/__init__.py b/viya_ark_library/templates/__init__.py
new file mode 100644
index 0000000..e69de29

View File

@@ -1,25 +0,0 @@
{ pkgs, ... }:
pkgs.python3Packages.buildPythonPackage rec {
pname = "viya4-ark";
version = "2.0.2";
src = fetchGit {
url = "git@github.com:sassoftware/viya4-ark.git";
ref = "main";
rev = "6a7864cd25c39c2ba1e06adbbd94ecebf9a5e3bf";
};
patches = [
./fix-setup.patch
./remove-kubeconfig-check.patch
];
propagatedBuildInputs = with pkgs.python3Packages; [
jinja2
pint
requests
pyyaml
ldap3
semantic-version
];
}

View File

@@ -1,96 +0,0 @@
diff --git a/pre_install_report/library/pre_install_check.py b/pre_install_report/library/pre_install_check.py
index 31b66d8..88a2d96 100644
--- a/pre_install_report/library/pre_install_check.py
+++ b/pre_install_report/library/pre_install_check.py
@@ -218,21 +218,6 @@ class ViyaPreInstallCheck():
output_dir)
return
- def _read_environment_var(self, env_var):
- """
- This method verifies that the KUBECONFIG environment variable is set.
-
- :param env_var: Environment variable to check
- """
- try:
- value_env_var = os.environ[env_var]
- except Exception:
- self.logger.exception("CalledProcessorError")
- print(viya_messages.KUBECONF_ERROR)
- sys.exit(viya_messages.BAD_ENV_RC_)
-
- return value_env_var
-
def _get_nested_info(self, nested_nodes, extracted_nodes, search_key):
try:
diff --git a/pre_install_report/pre_install_report.py b/pre_install_report/pre_install_report.py
index 1379c43..54fbc7e 100644
--- a/pre_install_report/pre_install_report.py
+++ b/pre_install_report/pre_install_report.py
@@ -74,24 +74,6 @@ def _read_config_file(filename):
sys.exit(viya_messages.SET_LIMTS_ERROR_RC_)
-def read_environment_var(env_var):
- """
- This method verifies that the KUBECONFIG environment variable is set.
-
- :param env_var: Environment variable to check
- """
- try:
- value_env_var = os.environ[env_var]
- # Check if specified file exists
- if not os.path.exists(value_env_var):
- print(viya_messages.KUBECONF_FILE_ERROR.format(value_env_var))
- sys.exit(viya_messages.BAD_ENV_RC_)
- except Exception:
- print(viya_messages.KUBECONF_ERROR)
- sys.exit(viya_messages.BAD_ENV_RC_)
- return value_env_var
-
-
class PreInstallReportCommand(Command):
"""
Command implementation for the pre-install command to register
@@ -198,7 +180,6 @@ def main(argv):
sas_logger = ViyaARKLogger(report_log_path, logging_level=logging_level, logger_name="pre_install_logger")
logger = sas_logger.get_logger()
- read_environment_var('KUBECONFIG')
try:
kubectl = Kubectl(namespace=name_space)
diff --git a/pre_install_report/test/test_pre_install_report.py b/pre_install_report/test/test_pre_install_report.py
index ed805ec..f93ec58 100644
--- a/pre_install_report/test/test_pre_install_report.py
+++ b/pre_install_report/test/test_pre_install_report.py
@@ -25,7 +25,6 @@ from pre_install_report.library.pre_install_check import ViyaPreInstallCheck
from pre_install_report.library.pre_install_check_permissions import PreCheckPermissions
from viya_ark_library.jinja2.sas_jinja2 import Jinja2TemplateRenderer
from viya_ark_library.logging import ViyaARKLogger
-from pre_install_report.pre_install_report import read_environment_var
from pre_install_report.library.utils import viya_messages
_SUCCESS_RC_ = 0
@@ -548,20 +547,6 @@ def test_get_calculated_aggregate_memory():
assert str(round(total_calc_memoryGi.to('Gi'), 13)) == '62.5229606628418 Gi'
-def test_kubconfig_file():
- old_kubeconfig = os.environ.get('KUBECONFIG') # /Users/cat/doc
- os.environ['KUBECONFIG'] = 'blah_nonexistentfile_blah'
- new_kubeconfig = os.environ.get('KUBECONFIG') # /Users/cat/doc
- assert new_kubeconfig == 'blah_nonexistentfile_blah'
- try:
- read_environment_var('KUBECONFIG')
- except SystemExit as exc:
- assert exc.code == viya_messages.BAD_ENV_RC_
- pass
- finally:
- os.environ['KUBECONFIG'] = str(old_kubeconfig)
-
-
def test_validated_k8s_server_version():
vpc = createViyaPreInstallCheck(viya_k8s_version_min,

View File

@@ -1,155 +0,0 @@
diff --git a/README.md b/README.md
index db2292b..400fbc2 100644
--- a/README.md
+++ b/README.md
@@ -24,7 +24,7 @@ Available Commands:
license Download a license for the given order number at the given cadence name and version
Flags:
- -c, --config string config file (default is $HOME/.viya4-orders-cli)
+ -c, --config string config file (default is $XDG_CONFIG_HOME/viya4-orders-cli/config.yaml)
-n, --file-name string name of the file where you want the downloaded order asset to be stored
(defaults:
certs - SASViyaV4_<order number>_certs.zip
@@ -144,7 +144,7 @@ Take the following steps to start using SAS Viya Orders CLI:
1. If you want to use a configuration file, create it.
- The default location for the configuration file is `$HOME/.viya4-orders-cli`.
+ The default location for the configuration file is `$XDG_CONFIG_HOME/viya4-orders-cli/config.yaml`.
You can save the file anywhere you want as long as you use the `--config` /
`-c` option to inform the CLI of any non-default location.
@@ -195,7 +195,7 @@ You have the following options for launching SAS Viya Orders CLI:
The examples in this section correspond to typical tasks that you might perform
using SAS Viya Orders CLI:
-- Using a configuration file, `/c/Users/auser/vocli/.viya4-orders-cli.yaml`, to
+- Using a configuration file, `/c/Users/auser/vocli/.config/viya4-orders-cli/config.yaml`, to
convey your API credentials, get deployment assets for SAS Viya order `923456`
at the latest version of the Long Term Support (`lts`) cadence. Send the
contents to file `/c/Users/auser/vocli/sasfiles/923456_lts_depassets.tgz`:
@@ -203,13 +203,13 @@ using SAS Viya Orders CLI:
```docker
docker run -v /c/Users/auser/vocli:/sasstuff viya4-orders-cli deploymentAssets 923456 lts \
- --config /sasstuff/.viya4-orders-cli.yaml --file-path /sasstuff/sasfiles --file-name 923456_lts_depassets
+ --config /sasstuff/.config/viya4-orders-cli/config.yaml --file-path /sasstuff/sasfiles --file-name 923456_lts_depassets
```
Sample output:
```text
- 2020/10/02 19:16:30 Using config file: /sasstuff/.viya4-orders-cli.yaml
+ 2020/10/02 19:16:30 Using config file: /sasstuff/.config/viya4-orders-cli/config.yaml
OrderNumber: 923456
AssetName: deploymentAssets
AssetReqURL: https://api.sas.com/mysas/orders/923456/cadenceNames/lts/deploymentAssets
diff --git a/cmd/root.go b/cmd/root.go
index ad221c9..9707ed7 100644
--- a/cmd/root.go
+++ b/cmd/root.go
@@ -8,7 +8,6 @@ import (
"log"
"os"
- homedir "github.com/mitchellh/go-homedir"
"github.com/sassoftware/viya4-orders-cli/lib/authn"
"github.com/spf13/cobra"
"github.com/spf13/viper"
@@ -48,7 +47,7 @@ func init() {
// Define global flags / options and set their default values.
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "",
- "config file (default is $HOME/.viya4-orders-cli)")
+ "config file (default is $XDG_CONFIG_HOME/viya4-orders-cli/config.yaml)")
rootCmd.PersistentFlags().StringVarP(&assetFileName, "file-name", "n", "",
"name of the file where you want the downloaded order asset stored\n"+
"(defaults:\n\tcerts - SASViyaV4_<order number>_certs.zip\n\tlicense and depassets - SASViyaV4_<order number>_<renewal sequence>_<cadence information>_<asset name>_<date time stamp>."+
@@ -74,16 +73,9 @@ func initConfig() {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
- // Find home directory.
- home, err := homedir.Dir()
- if err != nil {
- log.Fatalln("ERROR: homedir.Dir() returned: " + err.Error())
- }
-
- // Search config in home directory with name ".viya4-orders-cli" (without extension).
- viper.AddConfigPath(home)
- viper.SetConfigName(".viya4-orders-cli")
- // If they provide a config file with no extension if must be in yaml format.
+ viper.AddConfigPath("$XDG_CONFIG_HOME/viya4-orders-cli")
+ viper.AddConfigPath("$HOME/.config/viya4-orders-cli")
+ viper.SetConfigName("config")
viper.SetConfigType("yaml")
}
diff --git a/go.mod b/go.mod
index fbb9bb4..5008b3b 100644
--- a/go.mod
+++ b/go.mod
@@ -3,7 +3,6 @@ module github.com/sassoftware/viya4-orders-cli
go 1.19
require (
- github.com/mitchellh/go-homedir v1.1.0
github.com/spf13/cobra v1.6.1
github.com/spf13/viper v1.15.0
golang.org/x/oauth2 v0.5.0
diff --git a/go.sum b/go.sum
index 2f4164a..507c254 100644
--- a/go.sum
+++ b/go.sum
@@ -140,8 +140,6 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
-github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
-github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU=
diff --git a/lib/authn/authn.go b/lib/authn/authn.go
index a35c405..6345b6f 100644
--- a/lib/authn/authn.go
+++ b/lib/authn/authn.go
@@ -7,10 +7,10 @@ package authn
import (
"context"
- "encoding/base64"
"errors"
"fmt"
"net/url"
+ "os"
"strings"
"github.com/spf13/viper"
@@ -26,15 +26,20 @@ const (
// GetBearerToken calls the /token SAS Viya Orders API endpoint to exchange client credentials for a Bearer token.
// The client credentials are obtained from the SAS API Portal (https://apiportal.sas.com), and should be defined in
-// Viper (https://github.com/spf13/viper) as clientCredentialsId (key) and clientCredentialsSecret (secret).
+// Viper (https://github.com/spf13/viper) as clientCredentialsIdFile (key file) and clientCredentialsSecretFile (secret file).
func GetBearerToken() (token string, err error) {
- id, err := base64.StdEncoding.DecodeString(viper.GetString("clientCredentialsId"))
+ idFile := viper.GetString("clientCredentialsIdFile")
+ secFile := viper.GetString("clientCredentialsSecretFile")
+
+ // read id and sec from the files
+ id, err := os.ReadFile(idFile)
if err != nil {
- return token, errors.New("ERROR: attempt to decode clientCredentialsId failed: " + err.Error())
+ return token, errors.New("ERROR: attempt to read client credentials ID file failed: " + err.Error())
}
- sec, err := base64.StdEncoding.DecodeString(viper.GetString("clientCredentialsSecret"))
+
+ sec, err := os.ReadFile(secFile)
if err != nil {
- return token, errors.New("ERROR: attempt to decode clientCredentialsSecret failed: " + err.Error())
+ return token, errors.New("ERROR: attempt to read client credentials secret file failed: " + err.Error())
}
// Build the request URL.

View File

@@ -1,26 +0,0 @@
{ pkgs, ... }:
pkgs.buildGoModule rec {
pname = "viya4-orders-cli";
version = "1.6.0";
src = fetchGit {
url = "git@github.com:sassoftware/viya4-orders-cli.git";
ref = "main";
rev = "44fb3c4f1c3773679592f0b923ac1d1945b976ec";
};
vendorHash = "sha256-iDNSV+oYNela4kFtkLppUIL5/hR1dEbPPuOlN5a5MfE=";
patches = [ ./better-config.patch ];
ldflags = [
"-s"
"-w"
"-X github.com/sassoftware/viya4-orders-cli/cmd.version=${version}"
];
installPhase = ''
mkdir -p $out/bin
cp "$GOPATH/bin/viya4-orders-cli" $out/bin/viya4-orders-cli
'';
}

View File

@@ -0,0 +1,16 @@
{
user ? throw "user argument is required",
home ? throw "home argument is required",
}:
{
inputs,
pkgs,
system,
...
}:
let
selfPkgs = inputs.self.packages.${system};
in
{
home-manager.users.${user}.home.packages = [ selfPkgs.viya4-ark ];
}

View File

@@ -2,8 +2,15 @@
user ? throw "user argument is required",
home ? throw "home argument is required",
}:
{ config, pkgs, ... }:
{
config,
inputs,
pkgs,
system,
...
}:
let
selfPkgs = inputs.self.packages.${system};
hmConfig = config.home-manager.users.${user};
in
{
@@ -13,7 +20,7 @@ in
"viya/orders-api/secret".sopsFile = ../../../../../../../secrets/sas/secrets.yaml;
};
home.packages = [ (pkgs.callPackage ./package.nix { }) ];
home.packages = [ selfPkgs.viya4-orders-cli ];
xdg.configFile."viya4-orders-cli/config.yaml".source =
(pkgs.formats.yaml { }).generate "config.yaml"