Skip to content

Comments

Added feature to make json file for directory structure relevant to Issue #31#32

Open
yashpss01 wants to merge 6 commits intovedpawar2254:mainfrom
yashpss01:feature/treeInJsonFile
Open

Added feature to make json file for directory structure relevant to Issue #31#32
yashpss01 wants to merge 6 commits intovedpawar2254:mainfrom
yashpss01:feature/treeInJsonFile

Conversation

@yashpss01
Copy link
Contributor

Description

Adds functionality to output structure directory in a JSON file named treeview.json.

Related Issue

Adds feature mentioned in Issue #31

Testing

Run scripts for various local directories

Checklist

  • Code follows project style.
  • Self-reviewed the changes.
  • Updated docs if necessary.
  • Tests added or updated.
  • All tests pass.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @yashpss01, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the treeview CLI tool by adding the capability to persist the generated directory structure into a treeview.json file. It also refines the existing JSON output, making it more descriptive and programmatically accessible, thereby improving the tool's utility for automation and data processing workflows.

Highlights

  • New Feature: Output to JSON File: Introduced a new command-line option, --as-json-file, which allows users to create or overwrite a treeview.json file containing the directory structure as a nested JSON object.
  • Enhanced JSON Output Format: The JSON output format for both --as-json and the new --as-json-file option has been updated to provide a more detailed and structured representation, including path, name, type (directory/file), and children properties for each entry.
  • Documentation Updates: The README.md has been updated to include the new --as-json-file option and an example of its usage, along with an updated example of the new, more detailed JSON output structure.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Overview

Greptile Summary

This PR implements a new --as-json-file CLI flag that writes the directory tree structure to a treeview.json file, addressing feature request #31. The implementation refactors the JSON generation logic, renaming printTreeAsJson to treeAsJson and restructuring the output format from simple nested objects to a metadata-rich schema with explicit path, name, type, and children properties for each node. This change affects all three core files: bin/index.js adds the new CLI argument parsing, src/tree.js implements the JSON building and file-writing logic, and README.md documents the new feature with updated examples. The new JSON structure provides richer information for programmatic consumers while maintaining backward compatibility through the separate --as-json-file flag alongside the existing --as-json option.

PR Description Notes:

  • Line 1: Typo - "structure directory" should be "directory structure"

Important Files Changed

Filename Score Overview
src/tree.js 2/5 Refactored JSON generation logic and added file-writing capability, but uses async fs.writeFile without awaiting completion, risking data loss
bin/index.js 4/5 Added --as-json-file flag parsing and help text following existing patterns, but lacks validation for conflicting flags
README.md 3/5 Documented new feature with updated JSON examples, but contains syntax errors: missing backtick on line 19 and grammar issue on line89

Confidence score: 2/5

  • This PR requires careful review due to critical file-writing issues that could cause data loss in production use
  • Score lowered significantly due to: (1) async fs.writeFile call without promise handling that may cause incomplete file writes when the CLI exits immediately, (2) code duplication in tree construction logic between asJson and asJsonFile branches, (3) documentation syntax errors that need correction, and (4) lack of mutual exclusion logic when both --as-json and --as-json-file are specified
  • Pay close attention to src/tree.js lines 169-177 where the file write operation needs to be converted to fs.writeFileSync or properly awaited with async/await to ensure data integrity

Sequence Diagram

sequenceDiagram
    participant User
    participant CLI as "bin/index.js"
    participant TreeModule as "src/tree.js"
    participant FS as "File System"

    User->>CLI: "Execute treeview --as-json-file"
    CLI->>CLI: "parseArgs()"
    CLI->>TreeModule: "runTree(cwd, files, patterns, dirsOnly, asJson, asJsonFile)"
    TreeModule->>TreeModule: "getIgnoreList(startPath, additionalFiles, additionalPatterns)"
    TreeModule->>FS: "Check for .gitignore"
    FS-->>TreeModule: "Return .gitignore content (if exists)"
    TreeModule->>TreeModule: "Build ignoreConfig with exact matches and glob patterns"
    TreeModule->>TreeModule: "treeAsJson(startPath, ignoreConfig, dirsOnly)"
    TreeModule->>FS: "readdirSync(dirPath)"
    FS-->>TreeModule: "Return directory items"
    TreeModule->>TreeModule: "Filter items using shouldIgnoreItem()"
    loop For each item
        TreeModule->>FS: "statSync(fullPath)"
        FS-->>TreeModule: "Return file stats"
        alt Item is directory
            TreeModule->>TreeModule: "Recursively call treeAsJson()"
        end
    end
    TreeModule->>TreeModule: "Build nested JSON tree structure"
    TreeModule->>FS: "writeFile('treeview.json', JSON)"
    FS-->>TreeModule: "File write confirmation"
    TreeModule->>User: "console.log('File written successfully')"
Loading

3 files reviewed, 5 comments

Edit Code Review Agent Settings | Greptile

* `--ignore-pattern` → Ignore files matching glob patterns
* `--dirs-only` → Show only directories
* `--as-json` → Output as a nested JSON object
* `--as-json-file` → Create/overwrite current folder structure as a nested JSON object in a JSON file `treeview.json'
Copy link

Choose a reason for hiding this comment

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

syntax: missing closing backtick after treeview.json

Suggested change
* `--as-json-file` → Create/overwrite current folder structure as a nested JSON object in a JSON file `treeview.json'
* `--as-json-file` → Create/overwrite current folder structure as a nested JSON object in a JSON file `treeview.json`
Prompt To Fix With AI
This is a comment left during a code review.
Path: README.md
Line: 19:19

Comment:
**syntax:** missing closing backtick after `treeview.json`

```suggestion
  * `--as-json-file` → Create/overwrite current folder structure as a nested JSON object in a JSON file `treeview.json`
```

How can I resolve this? If you propose a fix, please make it concise.

treeview --as-json
```

### Create/Overwrite a file name `treeview.json` with folder structure as a JSON object
Copy link

Choose a reason for hiding this comment

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

syntax: typo: 'name' should be 'named'

Suggested change
### Create/Overwrite a file name `treeview.json` with folder structure as a JSON object
### Create/Overwrite a file named `treeview.json` with folder structure as a JSON object
Prompt To Fix With AI
This is a comment left during a code review.
Path: README.md
Line: 89:89

Comment:
**syntax:** typo: 'name' should be 'named'

```suggestion
### Create/Overwrite a file named `treeview.json` with folder structure as a JSON object
```

How can I resolve this? If you propose a fix, please make it concise.

--help, -h Show this help message
--dirs-only Show only directories, no files
--as-json Show tree as a nested JSON object
--as-json-file Creates/Overwrites JSON folder structure in treeview.json
Copy link

Choose a reason for hiding this comment

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

style: trailing whitespace after 'treeview.json'; consider removing for consistency

Prompt To Fix With AI
This is a comment left during a code review.
Path: bin/index.js
Line: 50:50

Comment:
**style:** trailing whitespace after 'treeview.json'; consider removing for consistency

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +170 to +177
fs.writeFile('treeview.json', JSON.stringify(tree, null, 2), (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully');
}
);
Copy link

Choose a reason for hiding this comment

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

logic: async file write without waiting causes the process to exit before file creation completes; use fs.writeFileSync instead to ensure the file is written

Suggested change
fs.writeFile('treeview.json', JSON.stringify(tree, null, 2), (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully');
}
);
fs.writeFileSync('treeview.json', JSON.stringify(tree, null, 2));
console.log('File written successfully');
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/tree.js
Line: 170:177

Comment:
**logic:** async file write without waiting causes the process to exit before file creation completes; use `fs.writeFileSync` instead to ensure the file is written

```suggestion
    fs.writeFileSync('treeview.json', JSON.stringify(tree, null, 2));
    console.log('File written successfully');
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +151 to +168
if (asJson){
const tree = {
"path": startPath,
"name": path.basename(startPath),
"type": "directory",
"children": treeAsJson(startPath, ignoreConfig, dirsOnly)
}

console.log(JSON.stringify(tree, null, 2))

}
else if (asJsonFile){
const tree = {
"path": startPath,
"name": path.basename(startPath),
"type": "directory",
"children": treeAsJson(startPath, ignoreConfig, dirsOnly)
}
Copy link

Choose a reason for hiding this comment

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

style: identical tree construction duplicated in both branches; extract to a helper function or create once before the if/else check

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/tree.js
Line: 151:168

Comment:
**style:** identical tree construction duplicated in both branches; extract to a helper function or create once before the if/else check

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a useful feature for outputting the directory structure to a JSON file. The implementation is straightforward, and the update to the JSON format to be more structured is a great improvement.

My review includes a few points:

  • A critical issue in src/tree.js regarding the use of asynchronous file I/O, which could lead to corrupted output files.
  • A suggestion to reduce code duplication in the same file to improve maintainability.
  • Minor fixes for documentation in README.md and bin/index.js.

Additionally, while the checklist in the pull request description indicates that tests have been added or updated, I don't see any changes to the test files. It would be beneficial to add a new test case to test.js to cover the new --as-json-file functionality to prevent future regressions.

Comment on lines +169 to +177
//logic for creating/overwriting folder structure as JSON object in treeview.js
fs.writeFile('treeview.json', JSON.stringify(tree, null, 2), (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully');
}
);
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

There are a few issues in this block:

  • Asynchronous File I/O Bug: fs.writeFile is asynchronous. In a CLI script, the process can exit before the file write operation is complete, leading to an empty or incomplete file. This is a critical bug. You should use fs.writeFileSync instead.
  • Insufficient Error Handling: The callback for fs.writeFile logs an error but doesn't exit the process with a non-zero status code. This can be misleading for users or automated scripts, as they might assume the operation succeeded.
  • Inaccurate Comment: The comment on line 169 is inaccurate and can be removed.

I suggest using fs.writeFileSync inside a try...catch block to address these issues.

    try {
      fs.writeFileSync('treeview.json', JSON.stringify(tree, null, 2));
      console.log('File "treeview.json" written successfully.');
    } catch (err) {
      console.error('Error writing file:', err);
      process.exit(1);
    }

Comment on lines +152 to +157
const tree = {
"path": startPath,
"name": path.basename(startPath),
"type": "directory",
"children": treeAsJson(startPath, ignoreConfig, dirsOnly)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

high

This block of code to create the tree object is identical to the one in the else if (asJsonFile) block (lines 163-168). To avoid duplication and improve maintainability, you should create the tree object once before the if/else if conditions.

* `--ignore-pattern` → Ignore files matching glob patterns
* `--dirs-only` → Show only directories
* `--as-json` → Output as a nested JSON object
* `--as-json-file` → Create/overwrite current folder structure as a nested JSON object in a JSON file `treeview.json'
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

There's a typo at the end of this line. It uses a single quote (') instead of a backtick (` \).

Suggested change
* `--as-json-file` → Create/overwrite current folder structure as a nested JSON object in a JSON file `treeview.json'
* `--as-json-file` → Create/overwrite current folder structure as a nested JSON object in a JSON file `treeview.json`

--help, -h Show this help message
--dirs-only Show only directories, no files
--as-json Show tree as a nested JSON object
--as-json-file Creates/Overwrites JSON folder structure in treeview.json
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The help text for this new option is not aligned with the others, which affects readability. Please adjust the spacing to align it with the other options.

Suggested change
--as-json-file Creates/Overwrites JSON folder structure in treeview.json
--as-json-file Creates/Overwrites JSON folder structure in treeview.json

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.

1 participant