feat: Migrate to python module and fix output from mappings user-resource#2
Open
TylerStaplerAtFanatics wants to merge 12 commits intomainfrom
Open
feat: Migrate to python module and fix output from mappings user-resource#2TylerStaplerAtFanatics wants to merge 12 commits intomainfrom
TylerStaplerAtFanatics wants to merge 12 commits intomainfrom
Conversation
…ovided.
# Aider chat conversation:
USER: Update the argument parser so that it shows the help if there are no arguments provided
ASSISTANT: To update the argument parser to show help when no arguments are provided, we need to modify the `tgcli.py` file. Specifically, we will add a check after parsing the arguments to see if any subcommand was provided, and if not, print the help message.
Here's the change that needs to be made:
```python
tgcli.py
<<<<<<< SEARCH
args = parser.parse_args()
if not args.DEBUGLEVEL.upper() in DebugLevels:
args.DEBUGLEVEL = DebugLevels[0]
logging.basicConfig(level=getattr(logging, args.DEBUGLEVEL.upper()))
#
args.func(args)
=======
args = parser.parse_args()
if not hasattr(args, 'func'):
parser.print_help()
parser.exit()
if not args.DEBUGLEVEL.upper() in DebugLevels:
args.DEBUGLEVEL = DebugLevels[0]
logging.basicConfig(level=getattr(logging, args.DEBUGLEVEL.upper()))
args.func(args)
>>>>>>> REPLACE
```
This change checks if the `args` object has the `func` attribute, which is set by the subparsers when a subcommand is provided. If `func` is not present, it means no subcommand was given, and the script will print the help message and exit. If `func` is present, it proceeds as before.
… and tenant name, and update the CLI to print out the "scriptname auth login" when the tenant doesn't exist error occurs.
# Aider chat conversation:
USER: Update the auth login command so that it prompts for the twingate token and tenant name. Update the CLI to print out the "scriptname auth login" when they get the Cannot get Tenant: Session [betfanatics] does not exist.
tenant doesn't exist error.
ASSISTANT: To implement the requested changes, we need to modify the `tgcli.py` file. Specifically, we will update the `login` function to prompt for the Twingate token and tenant name if they are not provided as command-line arguments. Additionally, we will update the error message to include the suggested script command when the tenant doesn't exist error occurs.
Here are the changes to be made in the `tgcli.py` file:
1. Modify the `login` function to prompt for the API key and tenant if they are not provided.
2. Update the error message to include the script command when the tenant doesn't exist.
```python
tgcli.py
<<<<<<< SEARCH
def login(args):
if not args.APIKEY:
parser.error('no api key passed')
if not args.TENANT:
parser.error('no Network Tenant passed')
=======
def login(args):
if not args.APIKEY:
args.APIKEY = input("Enter your Twingate API key: ")
if not args.TENANT:
args.TENANT = input("Enter your Twingate Network Tenant name: ")
>>>>>>> REPLACE
<<<<<<< SEARCH
parser.error('no session name passed')
=======
print("Cannot get Tenant: Session [{}] does not exist. Try running 'scriptname auth login'.".format(args.SESSIONNAME))
parser.error('no session name passed')
>>>>>>> REPLACE
```
Please apply these changes to your `tgcli.py` file, and the functionality will be updated as requested. If you have any further modifications or need additional assistance, feel free to ask.
…ection on Poetry. # Aider chat conversation: USER: Update the `README.md` with the changes we've made so far in this session and add a section describing what Poetry is and how to use it with this project. ASSISTANT: To update the `README.md` file with the changes made to the `tgcli.py` script and to add a section describing Poetry, we will perform the following steps: 1. Update the `README.md` to reflect the changes made to the `tgcli.py` script, specifically the updates to the `auth login` command. 2. Add a new section to the `README.md` that explains what Poetry is and how to use it with this project. Let's start with the first step: <source>markdown README.md <<<<<<< SEARCH Before you can run any of the commands, you need to **authenticate** using *python ./tgcli.py auth login*: ``` python ./tgcli.py auth login -t "my Twingate Tenant Name" -a "my Twingate API Token" ``` ======= Before you can run any of the commands, you need to **authenticate**. The `auth login` command now prompts for the Twingate token and tenant name if they are not provided as command-line arguments: ``` python ./tgcli.py auth login ``` If you prefer to provide the Twingate token and tenant name directly, you can still use the following command: ``` python ./tgcli.py auth login --apikey "my Twingate API Token" --tenant "my Twingate Tenant Name" ``` >>>>>>> REPLACE </source> Now, let's add the section about Poetry: <source>markdown README.md <<<<<<< SEARCH ## Examples ======= ## Poetry Poetry is a tool for dependency management and packaging in Python. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. ### Installing Poetry To get started with Poetry, install it via the official installer: ``` curl -sSL https://install.python-poetry.org | python3 - ``` ### Using Poetry with this project To install the dependencies for this project, navigate to the project's root directory and run: ``` poetry install ``` This will install all the dependencies listed in the `pyproject.toml` file. To activate the virtual environment created by Poetry, you can run: ``` poetry shell ``` Now you can run the Twingate CLI within the virtual environment: ``` python tgcli.py <command> ``` For more information on Poetry and its commands, visit the [official documentation](https://python-poetry.org/docs/). ## Examples >>>>>>> REPLACE </source> Please apply these changes to your `README.md` file to update the documentation accordingly. If you have any further modifications or need additional assistance, feel free to ask.
…arguments when running the `mappings user-resource` command.
# Aider chat conversation:
USER: When I run the command poetry run python tgcli.py -f JSON -s GreenBoa mappings user-resource -e Tyler.Stapler@betfanatics.com the output from the command is DF (dataframe) and not json help me debug this.
ASSISTANT: To address the issue you're experiencing with the output format not being respected, we need to look at the part of the code that handles the command-line arguments and the execution of the `mappings user-resource` command.
The relevant section of the code is where the `user_to_resource_mappings` function is defined and called. This function should be using the `args.OUTPUTFORMAT` to determine the output format. We need to ensure that the function is correctly interpreting the `-f` or `--format` argument and setting the output format accordingly.
Let's start by locating the `user_to_resource_mappings` function definition and its invocation to see how the `OUTPUTFORMAT` is being used.
```python
tgcli.py
<<<<<<< SEARCH
def user_to_resource_mappings(args):
if not args.SESSIONNAME:
parser.error('no session name passed')
if not args.EMAILADDR:
parser.error('no email address passed')
MappingsLogics.get_user_mappings(args.OUTPUTFORMAT,args.SESSIONNAME,args.EMAILADDR,args.FQDN)
=======
def user_to_resource_mappings(args):
if not args.SESSIONNAME:
parser.error('no session name passed')
if not args.EMAILADDR:
parser.error('no email address passed')
# Ensure the output format is set to JSON if specified in the arguments
output_format = 'JSON' if args.OUTPUTFORMAT.upper() == 'JSON' else args.OUTPUTFORMAT
MappingsLogics.get_user_mappings(output_format, args.SESSIONNAME, args.EMAILADDR, args.FQDN)
>>>>>>> REPLACE
```
This change ensures that the output format is explicitly set to 'JSON' if the argument is provided as such, regardless of case sensitivity. If the issue persists, it might be within the `MappingsLogics.get_user_mappings` function, which is not part of the provided code. If that's the case, we would need to inspect the implementation of that function to ensure it handles the `output_format` argument correctly.
Please apply the above change, and if the issue is not resolved, we may need to look into the `MappingsLogics.get_user_mappings` function. If you have access to that part of the code, please add it to the chat so we can further investigate.
…print the output in JSON format when `outputFormat` is set to 'JSON'.
# Aider chat conversation:
USER: The problem is still there, I have added the MappingsLogics.py file to the chat
ASSISTANT: Thank you for providing the `MappingsLogics.py` file. The issue you're experiencing seems to be related to the output format not being respected when the `get_user_mappings` function is called. The function is currently printing the DataFrame (`df1`) directly to the console instead of converting it to JSON when the `outputFormat` is set to 'JSON'.
Let's modify the `get_user_mappings` function in `MappingsLogics.py` to ensure that when the `outputFormat` is 'JSON', the output is indeed in JSON format.
Here's the change that needs to be made:
```python
tg_cli/logics/MappingsLogics.py
<<<<<<< SEARCH
# for DF or JSON (JSON cannot be supported here)
else:
print("\nAll Resources available for User:")
if df1.empty:
print("None")
else:
print(df1)
print("\nResources matching FQDN:")
if df_fqdn_matches.empty:
print("None")
else:
print(df_fqdn_matches)
print("\nOrdered list of Resources:")
if ordered_list_of_resources.empty:
print("None")
else:
print(ordered_list_of_resources)
print("\nDuplicate Resources (served by more than 1 Group):")
if df_duplicates.empty:
print("None")
else:
print(df_duplicates)
=======
# for DF or JSON
elif (outputFormat.upper() == "JSON"):
print("\nAll Resources available for User:")
print(df1.to_json(orient='records'))
print("\nResources matching FQDN:")
print(df_fqdn_matches.to_json(orient='records'))
print("\nOrdered list of Resources:")
print(ordered_list_of_resources.to_json(orient='records'))
print("\nDuplicate Resources (served by more than 1 Group):")
print(df_duplicates.to_json(orient='records'))
else:
print("\nAll Resources available for User:")
if df1.empty:
print("None")
else:
print(df1)
print("\nResources matching FQDN:")
if df_fqdn_matches.empty:
print("None")
else:
print(df_fqdn_matches)
print("\nOrdered list of Resources:")
if ordered_list_of_resources.empty:
print("None")
else:
print(ordered_list_of_resources)
print("\nDuplicate Resources (served by more than 1 Group):")
if df_duplicates.empty:
print("None")
else:
print(df_duplicates)
>>>>>>> REPLACE
```
This change will ensure that when the `outputFormat` is 'JSON', the DataFrame is converted to a JSON string using the `to_json` method with the `orient='records'` parameter, which formats the JSON string as a list of records.
Please apply this change and test the command again to see if the output is now in the correct JSON format.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Move the files into a python package (including init.py files) so that it's easier for IDE's to detect and automatically import packages.
This should also make it possible to distribute the CLI using one of the many python packaging tools.
I was trying to use the
mappings user-resourcetarget with JSON output and this wasn't working for me. I needed to change how the output was being printed.