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

#36: fixed JSON generation #38

Merged
merged 1 commit into from
Jun 24, 2024
Merged

Conversation

berickus
Copy link
Collaborator

@berickus berickus commented Jun 24, 2024

Summary by CodeRabbit

  • New Features

    • Integrated the dkjson library for enhanced JSON encoding and decoding capabilities.
    • Added support for LPeg-based JSON parsing.
  • Refactor

    • Simplified JSON handling in the app by replacing custom functions with dkjson functions.
  • Chores

    • Updated embeds.xml to include a reference to the dkjson.lua script for JSON handling.

@berickus berickus linked an issue Jun 24, 2024 that may be closed by this pull request
Copy link

coderabbitai bot commented Jun 24, 2024

Walkthrough

The updates focus on integrating the dkjson library for JSON handling in Lua scripts. This involves importing the dkjson library, leveraging its JSON encoding/decoding capabilities, and removing custom JSON handling functions. Additionally, new tags are added in embeds.xml to reference the dkjson.lua script.

Changes

File Summary of Changes
Libs/dkjson/dkjson.lua Added JSON module with functions for encoding, decoding, and enhancing JSON handling using LPeg and custom encoding exceptions.
embeds.xml Added reference to dkjson.lua script.
main.lua Imported dkjson, replaced custom JSON functions with dkjson functions, and refactored functions for JSON encoding.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Main
    participant dkjson

    User->>Main: Call showall()
    Main->>dkjson: Encode JSON data
    dkjson->>Main: Return encoded JSON
    Main->>User: Display JSON data

    User->>Main: Call GetUpdatedListingsJson()
    Main->>dkjson: Encode updated listings to JSON
    dkjson->>Main: Return encoded listings
    Main->>User: Display updated listings
Loading

Poem

In Lua's land, where scripts do dance,
A JSON library got its chance.
No more custom strings to write,
dkjson makes it all so bright.
With LPeg's aid, it parses fast,
Our code is clean and built to last.
🎉📜🍃


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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

@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: 4

Outside diff range and nitpick comments (1)
main.lua (1)

107-107: Improve user feedback

The clear function resets the auctions table and prints a message. It might be beneficial to also confirm the action in the UI, not just the console, to enhance user experience.

Consider adding a UI popup or a more visible notification method.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ba087f8 and df36aed.

Files ignored due to path filters (1)
  • Libs/dkjson/.DS_Store is excluded by !**/.DS_Store
Files selected for processing (3)
  • Libs/dkjson/dkjson.lua (1 hunks)
  • embeds.xml (1 hunks)
  • main.lua (9 hunks)
Files skipped from review due to trivial changes (1)
  • embeds.xml
Additional comments not posted (4)
main.lua (2)

Line range hint 79-101: Refactor JSON encoding and output handling

The showall function constructs JSON manually, which might lead to errors or inefficient processing. Using dkjson.encode directly on the UndercutJsonTable could simplify this significantly.

[REFACTOR_SUGGESTion]

function Saddlebag:showall()
    local output = dkjson.encode(UndercutJsonTable or {}, {indent = true})
    local af = Saddlebag:auctionButton("")
    Saddlebag.sf:SetText(output)
    af:Show()
end

216-217: Redundant UI updates

The handler function updates the UI every time it's called, which could be optimized. Consider checking if the data has changed before updating the UI to avoid unnecessary operations.

[PERFORMANCE]

function Saddlebag:handler(msg, SaddlebagEditBox)
    if msg == 'help' then
        message('Go to the auction house, view your auctions and then click the pop up button or run /sbex')
    else
+       local newData = Saddlebag:GetUpdatedListingsJson()
+       if Saddlebag.sf:GetText() ~= newData then
            local af = Saddlebag:auctionButton("")
            Saddlebag.sf:SetText(newData)
            af:Show()
+       end
    end
end
Libs/dkjson/dkjson.lua (2)

1-3: Library versioning and loading

You're using LibStub for version control, which is good practice. Ensure that the versioning is actively managed and updated with each change to the library to prevent compatibility issues.


606-712: LPeg integration for JSON parsing

The use of LPeg to enhance JSON parsing capabilities is a significant improvement. However, ensure that error handling around LPeg's version issues (line 609) and the conditional use of LPeg (lines 714-716) are robust and tested, especially across different environments where LPeg might not be available.

Verification successful

LPeg integration for JSON parsing

The provided code snippet includes the necessary error handling for LPeg version issues (line 609) and the conditional use of LPeg (lines 714-716). The error handling code for LPeg version issues is present and matches the review comment. Similarly, the conditional use of LPeg is correctly implemented as described in the review comment.

  • Line 609: error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
  • Lines 714-716: json.use_lpeg and json.using_lpeg for conditional use of LPeg.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify robust error handling for LPeg integration.

# Test: Search for error handling related to LPeg version issues.
rg --type lua 'error "due to a bug in LPeg 0.11"'

Length of output: 51

Comment on lines +204 to +206
return dkjson.json.encode(storage, { indent = true })
else
print(
"ERROR! Make sure you are at the auction house looking at your auctions before you click the button or run /sbex")
print("{}")
print("ERROR! Make sure you are at the auction house looking at your auctions before you click the button or run /sbex")
Copy link

Choose a reason for hiding this comment

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

Error handling in GetUpdatedListingsJson

The function prints an error message directly to the console. It would be better to handle this scenario more gracefully, possibly by throwing a custom error or handling it in the UI.

Consider improving the error handling mechanism to provide a better user experience.

@@ -395,6 +326,7 @@ function Saddlebag:auctionButton(text)
sf:SetFullWidth(true)
sf:SetText(text)
sf:HighlightText()
Saddlebag.sf = sf
Copy link

Choose a reason for hiding this comment

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

Global variable exposure

The assignment Saddlebag.sf = sf exposes sf as a global variable which could lead to unintended side effects if other parts of the program modify it.

Consider encapsulating this variable more securely within the module or class.

@@ -7,6 +7,7 @@ local addonName = "Saddlebag Exchange Undercut Alerts"
Saddlebag = LibStub("AceAddon-3.0"):NewAddon(Saddlebag, "Saddlebag", "AceConsole-3.0", "AceEvent-3.0")
local AceGUI = LibStub("AceGUI-3.0")
LibRealmInfo = LibStub("LibRealmInfo")
local dkjson = LibStub("dkjson")
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ensure dkjson is properly loaded

The search results indicate that dkjson is loaded using LibStub and is subsequently used in the code. However, there is no explicit error handling or initialization check for dkjson. It would be prudent to add a check to ensure dkjson is loaded correctly before using it to avoid potential runtime errors.

  • main.lua:
    • Add a check to ensure dkjson is loaded successfully.
local dkjson = LibStub("dkjson")
if not dkjson then
    error("dkjson library not found")
end
Analysis chain

Ensure dkjson is properly loaded

You're using LibStub to load the dkjson library. It's crucial to ensure that the library is correctly initialized and available before using it to avoid runtime errors.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that dkjson library is correctly loaded and available.

# Test: Search for error handling related to dkjson loading.
rg --type lua 'if not dkjson then'

Length of output: 36



Script:

#!/bin/bash
# Description: Verify that dkjson library is correctly initialized and available.

# Search for all instances of LibStub usage related to dkjson.
rg --type lua 'LibStub\("dkjson"\)'

# Search for any error handling or initialization checks for dkjson.
rg --type lua 'dkjson'

# Search for the usage of dkjson to ensure it is used after being loaded.
rg --type lua 'dkjson\.' 

Length of output: 777

Comment on lines +592 to +603
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end

function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
Copy link

Choose a reason for hiding this comment

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

JSON decoding function enhancement

The json.decode function now supports custom metatables for objects and arrays, which is a useful feature for advanced JSON manipulation. Ensure that this functionality is covered by unit tests to prevent regressions in future updates.

Would you like me to help by adding unit tests for these new features?

@berickus berickus merged commit f50d20d into main Jun 24, 2024
@berickus berickus deleted the 36-show-all-generates-wrong-json branch June 24, 2024 09:23
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.

Show all generates wrong JSON
1 participant