44import random
55import string
66import logging
7-
7+ import re
88
99# Initialize logging
1010logging .basicConfig (
@@ -31,12 +31,12 @@ def get_random_key(args):
3131
3232def read_json (args ):
3333 path = args .path .split ('.' )
34- log .info (f'path={ path } ' )
34+ log .debug (f'path={ path } ' )
3535
3636 state = {}
3737 try :
3838 state_location = os .environ ["CB_STATE_DIR" ]
39- log .info (state_location )
39+ log .debug (state_location )
4040
4141 with open (f'{ state_location } /state.json' ) as state_file :
4242 state ["data" ] = json .load (state_file )
@@ -56,19 +56,54 @@ def read_json(args):
5656 print ()
5757
5858
59+ def filter_for_jdk (args ):
60+ # custom error
61+ class NoMatchFoundError (Exception ):
62+ def __init__ (self ):
63+ self .message = f'Error: No match found.'
64+ super ().__init__ (self .message )
65+
66+ # regex
67+ regex = '^openjdk-11.\d+.\d+'
68+ log .debug (f'Filtering using regex: { regex } ' )
69+
70+ # filtering inputs
71+ inputs = args .string
72+ log .debug (f'Filter from list: { str (inputs )} ' )
73+ f = re .compile (regex )
74+ matches = [ item for item in inputs if f .match (item ) ]
75+ log .debug (f'Matches foumd: { str (matches )} ' )
76+
77+ # processing results if matches found
78+ if len (matches ) > 0 :
79+ print (matches [0 ])
80+ else :
81+ raise NoMatchFoundError ()
82+
83+
5984# CLI (using argparse)
6085parser = argparse .ArgumentParser ()
6186sp = parser .add_subparsers (description = "Lab Utility Functions" )
6287parser .set_defaults (func = print_help )
6388
6489# Generate Token Parser
90+ # Used to generate random tokens
6591generate_token_parser = sp .add_parser ("generate-token" )
6692generate_token_parser .add_argument ("-l" , "--length" , default = 16 , help = "length of token to generate" , type = int )
6793generate_token_parser .set_defaults (func = get_random_key )
6894
69- generate_token_parser = sp .add_parser ("json" )
70- generate_token_parser .add_argument ("-p" , "--path" , required = True , help = "Json Path Expression" )
71- generate_token_parser .set_defaults (func = read_json )
95+ # JSON Parser
96+ # Used to parse the State file and read JSON keys instead of jq with better exception handling
97+ # This avoids the issue with JQ returning null instead of an empty value
98+ json_parser = sp .add_parser ("json" )
99+ json_parser .add_argument ("-p" , "--path" , required = True , help = "Json Path Expression" )
100+ json_parser .set_defaults (func = read_json )
101+
102+ # Regex Filter
103+ # Used by filtering csruntimectl JDK
104+ filter_parser = sp .add_parser ("filter" )
105+ filter_parser .add_argument ("-s" , "--string" , nargs = "+" , required = True , help = "Inputs to filter the JDK version from" )
106+ filter_parser .set_defaults (func = filter_for_jdk )
72107
73108# Process Parsed Arguments
74109options = parser .parse_args ()
0 commit comments