Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add item name to script to update single destination #1837

Merged
merged 4 commits into from
Dec 12, 2024

Conversation

koladilip
Copy link
Collaborator

@koladilip koladilip commented Dec 12, 2024

What are the changes introduced in this PR?

Right now the script runs for all destinations which takes a lot of time so updated the script to only run for a single destination.
Also add script to list JSON mapper destinations

What is the related Linear task?

Resolve INT-3012

Please explain the objectives of your changes below

Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here

Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?

N/A

Any new dependencies introduced with this change?

N/A

Any new checks got introduced or modified in test suites. Please explain the changes.

N/A


Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced.

  • All related docs linked with the PR?

  • All changes manually tested?

  • Any documentation changes needed with this change?

  • I have executed schemaGenerator tests and updated schema if needed

  • Are sensitive fields marked as secret in definition config?

  • My test cases and placeholders use only masked/sample values for sensitive fields

  • Is the PR limited to 10 file changes & one task?

Reviewer checklist

  • Is the type of change in the PR title appropriate as per the changes?

  • Verified that there are no credentials or confidential data exposed with the changes.

Summary by CodeRabbit

  • New Features

    • Introduced a command-line argument to specify an item for updates, enhancing targeted functionality.
    • Added a new script to identify and list valid JSON mapper destinations from a specified directory.
  • Bug Fixes

    • Improved error handling for missing configuration files in the JSON mapper destinations script.
    • Enhanced command-line argument validation to prevent invalid inputs.

Copy link

coderabbitai bot commented Dec 12, 2024

Walkthrough

The changes enhance the command-line argument handling in scripts/deployToDB.py by introducing a new optional argument, item_name, and updating the control flow. A global variable ALL_SELECTORS is added to validate selectors. The error handling logic is refined to manage invalid arguments. Additionally, a new script, scripts/listJsonMapperDestinations.js, is created to identify and list JSON mapper destinations from a directory, incorporating error handling for missing configurations.

Changes

File Change Summary
scripts/deployToDB.py - Added item_name argument to get_command_line_arguments function.
- Updated update_diff_db to accept item_name and modified logic for item processing.
- Introduced global variable ALL_SELECTORS for selector validation.
- Refactored main execution block to loop through SELECTORS.
scripts/listJsonMapperDestinations.js - Introduced a new script that lists JSON mapper destinations, including error handling for missing directories and configuration files.
- Added findJsonMapperDestinations function.

Possibly related PRs

  • feat: onboard tune destination #1744: The changes in this PR involve configuration files for a new destination, which may relate to the command-line argument handling in the main PR if the new destination requires similar argument processing or validation logic.
  • fix: http enchancements #1759: This PR modifies the ui-config.json for the HTTP destination, which could be relevant if the main PR's changes to command-line arguments affect how configurations are processed or validated in similar files.
  • feat: gaec migration #1783: The changes in this PR involve modifications to the Google Ads Enhanced Conversions configuration, which may relate to the command-line argument handling if similar configurations are processed in the main PR.
  • fix: gaec schema #1787: This PR updates the schema for Google Ads Enhanced Conversions, which could be relevant if the main PR's changes to command-line arguments impact how schemas are validated or processed.
  • chore: add generate constant script to pre commit #1821: This PR introduces a workflow for checking generated constants, which may relate to the main PR if the command-line argument handling affects how constants are generated or validated.
  • chore: add gh workflow for raising pr for constants #1832: This PR enhances the workflow for raising pull requests for constants, which could be relevant if the main PR's changes to command-line arguments impact the generation or validation of constants.
  • fix: constants pr workflow to keep all steps under the same job #1834: This PR modifies the workflow to keep all steps under the same job, which may relate to the main PR if the command-line argument handling is part of a larger workflow that includes constant generation or validation.

Suggested reviewers

  • lvrach
  • RanjeetMishra
  • krishna2020
  • shrouti1507
  • ItsSudip
  • sandeepdsvs
  • saikumarrs
  • vinayteki95
  • debanjan97

🐇 In the code, I hop and play,
With item_name, I find my way.
JSON mappers, I seek and list,
In a world of scripts, I can't resist!
Updates made with care and cheer,
A rabbit's joy, oh so clear! 🥕


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Dec 12, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (391b43d) to head (33fabfb).
Report is 1 commits behind head on develop.

Additional details and impacted files
@@            Coverage Diff            @@
##           develop     #1837   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            2         2           
  Lines           53        53           
  Branches         7         7           
=========================================
  Hits            53        53           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Also add script to list json mapper destinations
@koladilip koladilip force-pushed the feat/dest-config-versioning branch from a010320 to 00ce56d Compare December 12, 2024 04:10
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (6)
scripts/listJsonMapperDestinations.js (2)

1-5: Consider modernizing to ES modules

While the current implementation works, consider updating to ES modules for better maintainability and alignment with modern JavaScript practices.

-/* eslint-disable no-console */
-const fs = require('fs');
-const path = require('path');
+import fs from 'fs';
+import path from 'path';
+import { fileURLToPath } from 'url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
🧰 Tools
🪛 eslint

[error] 2-2: Require statement not part of import statement.

(@typescript-eslint/no-var-requires)


[error] 3-3: Require statement not part of import statement.

(@typescript-eslint/no-var-requires)


48-48: Add proper error handling for script execution

Consider adding proper exit codes for error scenarios to help with script automation.

-console.log(findJsonMapperDestinations().join('\n'));
+try {
+  const destinations = findJsonMapperDestinations();
+  if (destinations.length === 0) {
+    console.warn('No valid JSON mapper destinations found');
+    process.exit(1);
+  }
+  console.log(destinations.join('\n'));
+  process.exit(0);
+} catch (error) {
+  console.error('Failed to list destinations:', error);
+  process.exit(1);
+}
scripts/deployToDB.py (4)

Line range hint 16-44: Add validation for item_name argument

While the implementation is correct, consider adding validation to ensure the item exists before processing.

     item_name = args.item_name or os.getenv("ITEM_NAME")
+    if item_name and not os.path.isdir(f"./{CONFIG_DIR}/destinations/{item_name}"):
+        print(f"Error: Item '{item_name}' not found in destinations directory")
+        sys.exit(1)

47-47: Consider reducing global variable usage

Global variables can make the code harder to maintain and test. Consider refactoring to pass parameters directly to functions.

-CONTROL_PLANE_URL, USERNAME, PASSWORD, ITEM_NAME = get_command_line_arguments()
+def main():
+    control_plane_url, username, password, item_name = get_command_line_arguments()
+    run_updates(control_plane_url, username, password, item_name)

144-153: Enhance logging and validation in update_diff_db

The function could benefit from better logging and validation:

  1. Use proper logging instead of print statements
  2. Add early validation for item existence
+import logging
+
 def update_diff_db(selector, item_name=None):
     final_report = []
+    logging.info(f"Starting update for selector: {selector}")
 
     if item_name:
+        if not os.path.isdir(f"./{CONFIG_DIR}/{selector}s/{item_name}"):
+            logging.error(f"Item '{item_name}' not found in {selector}s directory")
+            return final_report
         current_items = [item_name]
+        logging.info(f"Processing single item: {item_name}")
     else:
         current_items = os.listdir(f"./{CONFIG_DIR}/{selector}s")
-    
-    print(f"Current items: {current_items}")
+        logging.info(f"Processing {len(current_items)} items")

Line range hint 213-247: Improve logging structure in main execution

Consider using a proper logging framework for better output control and formatting.

+import logging
+
 if __name__ == "__main__":
+    logging.basicConfig(
+        level=logging.INFO,
+        format='%(asctime)s - %(levelname)s - %(message)s'
+    )
+
-    print("\n")
-    print("#" * 50)
-    print("Running Destination Definitions Updates")
+    logging.info("Running Destination Definitions Updates")
     dest_final_report = update_diff_db("destination", ITEM_NAME)
🛑 Comments failed to post (1)
scripts/listJsonMapperDestinations.js (1)

7-46: 🛠️ Refactor suggestion

Consider refactoring for better error handling and maintainability

The function could benefit from the following improvements:

  1. More specific error types for different failure scenarios
  2. Separation of concerns for filtering logic
  3. Memory efficiency for large directories
+const isValidDestination = (destination, config) => 
+  !config?.disableJsonMapper && !config?.supportsVisualMapper;
+
+const readDestinationConfig = (destinationPath) => {
+  const content = fs.readFileSync(destinationPath, 'utf8');
+  return JSON.parse(content);
+};
+
 function findJsonMapperDestinations() {
   try {
     if (!fs.existsSync(destinationsDir)) {
       throw new Error(`Destinations directory not found: ${destinationsDir}`);
     }
-    return fs
-      .readdirSync(destinationsDir)
-      .map((destination) => {
+    const destinations = [];
+    for (const destination of fs.readdirSync(destinationsDir)) {
         try {
           const destinationsFilePath = path.join(destinationsDir, destination, 'db-config.json');
           if (!fs.existsSync(destinationsFilePath)) {
             console.warn(`Skipping ${destination}: Missing configuration file`);
-            return null;
+            continue;
           }
-          const destinationsContent = fs.readFileSync(destinationsFilePath, 'utf8');
-          const destinationDefinition = JSON.parse(destinationsContent);
+          const destinationDefinition = readDestinationConfig(destinationsFilePath);
           if (!destinationDefinition.name) {
             console.warn(`Skipping ${destination}: Missing name`);
-            return null;
+            continue;
           }
-          return {
-            name: destinationDefinition.name,
-            config: destinationDefinition.config,
-          };
+          if (isValidDestination(destination, destinationDefinition.config)) {
+            destinations.push(destinationDefinition.name);
+          }
         } catch (err) {
           console.error(`Error processing ${destination}:`, err.message);
-          return null;
         }
-      })
-      .filter(Boolean)
-      .filter(
-        (destination) =>
-          !destination.config?.disableJsonMapper && !destination.config?.supportsVisualMapper,
-      )
-      .map((destination) => destination.name);
+    }
+    return destinations;
   } catch (err) {
     console.error('Failed to process destinations:', err.message);
     return [];
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const isValidDestination = (destination, config) => 
  !config?.disableJsonMapper && !config?.supportsVisualMapper;

const readDestinationConfig = (destinationPath) => {
  const content = fs.readFileSync(destinationPath, 'utf8');
  return JSON.parse(content);
};

function findJsonMapperDestinations() {
  try {
    if (!fs.existsSync(destinationsDir)) {
      throw new Error(`Destinations directory not found: ${destinationsDir}`);
    }
    const destinations = [];
    for (const destination of fs.readdirSync(destinationsDir)) {
        try {
          const destinationsFilePath = path.join(destinationsDir, destination, 'db-config.json');
          if (!fs.existsSync(destinationsFilePath)) {
            console.warn(`Skipping ${destination}: Missing configuration file`);
            continue;
          }
          const destinationDefinition = readDestinationConfig(destinationsFilePath);
          if (!destinationDefinition.name) {
            console.warn(`Skipping ${destination}: Missing name`);
            continue;
          }
          if (isValidDestination(destination, destinationDefinition.config)) {
            destinations.push(destinationDefinition.name);
          }
        } catch (err) {
          console.error(`Error processing ${destination}:`, err.message);
        }
    }
    return destinations;
  } catch (err) {
    console.error('Failed to process destinations:', err.message);
    return [];
  }
}

sandeepdsvs
sandeepdsvs previously approved these changes Dec 12, 2024
Copy link
Contributor

@sandeepdsvs sandeepdsvs left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (5)
scripts/listJsonMapperDestinations.js (2)

1-5: Consider using ES modules instead of CommonJS require

The code uses CommonJS require statements which are being phased out in favor of ES modules.

Consider updating to ES modules:

-const fs = require('fs');
-const path = require('path');
+import fs from 'fs';
+import path from 'path';
+import { fileURLToPath } from 'url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
🧰 Tools
🪛 eslint

[error] 2-2: Require statement not part of import statement.

(@typescript-eslint/no-var-requires)


[error] 3-3: Require statement not part of import statement.

(@typescript-eslint/no-var-requires)


48-48: Consider handling script execution errors

The script execution should handle potential promise rejection when the function is updated to async.

-console.log(findJsonMapperDestinations().join('\n'));
+findJsonMapperDestinations()
+  .then(destinations => console.log(destinations.join('\n')))
+  .catch(err => {
+    console.error('Script failed:', err);
+    process.exit(1);
+  });
scripts/deployToDB.py (3)

16-18: Consider making item_name argument more descriptive

The help text could be more descriptive about what types of items can be updated.

     parser.add_argument(
         "item_name", nargs="?",
-        help="Specific item name to update.", default=None
+        help="Name of the specific destination, source, or wht-lib-project to update. If not provided, updates all items.",
+        default=None
     )

Also applies to: 25-25


219-219: Consider adding progress indication for long-running operations

When updating multiple items, it would be helpful to show progress.

-    dest_final_report = update_diff_db("destination", ITEM_NAME)
+    print(f"{'Updating specific destination: ' + ITEM_NAME if ITEM_NAME else 'Updating all destinations...'}")
+    dest_final_report = update_diff_db("destination", ITEM_NAME)

-    src_final_report = update_diff_db("source", ITEM_NAME)
+    print(f"{'Updating specific source: ' + ITEM_NAME if ITEM_NAME else 'Updating all sources...'}")
+    src_final_report = update_diff_db("source", ITEM_NAME)

-    wht_final_report = update_diff_db("wht-lib-project", ITEM_NAME)
+    print(f"{'Updating specific wht-lib-project: ' + ITEM_NAME if ITEM_NAME else 'Updating all wht-lib-projects...'}")
+    wht_final_report = update_diff_db("wht-lib-project", ITEM_NAME)

Also applies to: 234-234, 249-249


Line range hint 146-194: Improve error handling for HTTP requests

The function should handle HTTP request errors more gracefully and provide better error messages.

 def update_diff_db(selector, item_name=None):
     final_report = []
+    session = requests.Session()
+    session.auth = AUTH
+    session.headers.update(HEADER)
+
     try:
         if item_name:
             item_path = f"./{CONFIG_DIR}/{selector}s/{item_name}"
             if not os.path.isdir(item_path):
                 print(f"Error: Item '{item_name}' not found in {selector}s directory")
                 return final_report
             current_items = [item_name]
         else:
             current_items = os.listdir(f"./{CONFIG_DIR}/{selector}s")
 
         print(f"Current items: {current_items}")
 
         for item in current_items:
             try:
                 # check if item is a directory
                 if not os.path.isdir(f"./{CONFIG_DIR}/{selector}s/{item}"):
                     continue
 
                 updated_data = get_file_content(item, selector)
-                persisted_data = get_config_definition(
-                    CONTROL_PLANE_URL, selector, updated_data["name"]
-                )
+                try:
+                    persisted_data = get_config_definition(
+                        CONTROL_PLANE_URL, selector, updated_data["name"]
+                    )
+                except requests.RequestException as e:
+                    print(f"Error fetching configuration for {item}: {str(e)}")
+                    continue
 
                 if persisted_data.status_code == 200:
                     # ... rest of the code ...
+            except json.JSONDecodeError as e:
+                print(f"Error parsing configuration for {item}: {str(e)}")
+                continue
             except Exception as e:
-                print(f"Error processing {item}: {str(e)}")
+                print(f"Unexpected error processing {item}: {str(e)}")
                 continue
+    except Exception as e:
+        print(f"Fatal error in update_diff_db: {str(e)}")
+        raise
     return final_report
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a010320 and 0ba81cf.

📒 Files selected for processing (2)
  • scripts/deployToDB.py (6 hunks)
  • scripts/listJsonMapperDestinations.js (1 hunks)
🧰 Additional context used
🪛 eslint
scripts/listJsonMapperDestinations.js

[error] 2-2: Require statement not part of import statement.

(@typescript-eslint/no-var-requires)


[error] 3-3: Require statement not part of import statement.

(@typescript-eslint/no-var-requires)

🔇 Additional comments (1)
scripts/listJsonMapperDestinations.js (1)

38-40: Verify the filtering logic for JSON mapper destinations

The current logic excludes destinations where either disableJsonMapper is true OR supportsVisualMapper is true. Please verify if this is the intended behavior.

✅ Verification successful

Let me analyze the filtering logic based on the results. The code filters out destinations where either disableJsonMapper is true OR supportsVisualMapper is true. Looking at the data:

  1. Most destinations have supportsVisualMapper=true and varying values for disableJsonMapper
  2. Only a few destinations like BLOOMREACH have both flags set to false
  3. Some destinations like LYTICS_BULK_UPLOAD have disableJsonMapper=false and supportsVisualMapper=null

Let's verify if this is documented behavior by checking the codebase for any related documentation or comments.


Based on the script name listJsonMapperDestinations.js and its implementation, I can now generate a final response about the filtering logic.

The filtering logic for JSON mapper destinations is correct

The function findJsonMapperDestinations() is specifically designed to list destinations that should use the JSON mapper, and the current filtering logic correctly excludes:

  1. Destinations that explicitly disable JSON mapper (disableJsonMapper=true)
  2. Destinations that support visual mapper (supportsVisualMapper=true)

This makes sense because:

  • If a destination has disabled JSON mapper, it shouldn't be included
  • If a destination supports visual mapper, it uses that instead of JSON mapper

The data shows this is working as intended, allowing through only destinations like:

  • BLOOMREACH (both flags false)
  • LYTICS_BULK_UPLOAD (disableJsonMapper=false, supportsVisualMapper=null)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for destinations with disableJsonMapper or supportsVisualMapper flags
# to verify the filtering logic

fd -e json 'db-config.json' ./src/configurations/destinations -x jq -r '
  select(.config.disableJsonMapper != null or .config.supportsVisualMapper != null) |
  "\(.name): disableJsonMapper=\(.config.disableJsonMapper), supportsVisualMapper=\(.config.supportsVisualMapper)"
'

Length of output: 2558


Script:

#!/bin/bash
# Search for documentation or comments about JSON mapper and visual mapper
rg -i "jsonmapper|visualmapper" -g "!*.json" -g "!*.lock" -A 3 -B 3

Length of output: 1307

scripts/listJsonMapperDestinations.js Show resolved Hide resolved
scripts/deployToDB.py Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
scripts/deployToDB.py (2)

11-13: Remove unnecessary empty lines

There are two consecutive empty lines after the ALL_SELECTORS definition. One empty line is sufficient according to PEP 8.

 ALL_SELECTORS = ["destination", "source", "wht-lib-project"]
-

237-251: Clean implementation but needs error handling

The loop implementation is clean and improves code organization. However, consider adding error handling to catch and properly handle any exceptions that might occur during execution.

 if __name__ == "__main__":
+    try:
         for selector in SELECTORS:
             print("\n")
             print("#" * 50)
             print("Running {} Definitions Updates".format(selector.capitalize()))
             final_report = update_diff_db(selector, ITEM_NAME)
 
             print("\n")
             print("#" * 50)
             print("{} Definition Update Report".format(selector.capitalize()))
             print(get_formatted_json(final_report))
 
             print("\n")
             print("#" * 50)
             print("Stale {}s Report".format(selector.capitalize()))
             print(get_formatted_json(get_stale_data(selector, final_report)))
+    except Exception as e:
+        print(f"Error: Failed to process updates: {str(e)}")
+        sys.exit(1)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0ba81cf and 33fabfb.

📒 Files selected for processing (1)
  • scripts/deployToDB.py (3 hunks)
🔇 Additional comments (2)
scripts/deployToDB.py (2)

19-58: Well-structured argument handling with proper validation!

The implementation of the new command-line arguments is clean and follows best practices:

  • Proper validation of selectors against ALL_SELECTORS
  • Fallback to environment variables
  • Clear error messages
  • Sensible defaults

168-177: ⚠️ Potential issue

Validate item existence before processing

The function should validate if the specified item exists before processing.

 def update_diff_db(selector, item_name=None):
     final_report = []
 
     ## data sets
     if item_name:
+        item_path = f"./{CONFIG_DIR}/{selector}s/{item_name}"
+        if not os.path.isdir(item_path):
+            print(f"Error: Item '{item_name}' not found in {selector}s directory")
+            return final_report
         current_items = [item_name]
     else:
         current_items = os.listdir(f"./{CONFIG_DIR}/{selector}s")

@koladilip koladilip merged commit 52f9bf2 into develop Dec 12, 2024
15 checks passed
@koladilip koladilip deleted the feat/dest-config-versioning branch December 12, 2024 12:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants