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

GO-2746: add export structure #1451

Merged
merged 6 commits into from
Aug 13, 2024
Merged

Conversation

AnastasiaShemyakinskaya
Copy link
Member

Signed-off-by: AnastasiaShemyakinskaya <shem98a@mail.ru>
@AnastasiaShemyakinskaya AnastasiaShemyakinskaya marked this pull request as ready for review August 6, 2024 12:48
Copy link

coderabbitai bot commented Aug 6, 2024

Walkthrough

This update enhances the export module's functionality by introducing structured file handling through new directory constants and a dynamic file naming system based on smart block types. The makeFileName method has been extended for better organization, while robust tests ensure reliability. Additionally, file writing operations now create necessary directories if they don't exist, improving error handling and robustness. Overall, these changes streamline the export process and improve maintainability.

Changes

Files Change Summary
core/block/export/export.go,
core/block/export/writer.go,
core/block/export/export_test.go
Introduced new constants for directory paths, modified makeFileName and makeMarkdownName for dynamic naming based on blockType, added new method provideFileDirectory, and enhanced WriteFile to create directories as needed. Comprehensive tests for filename generation added.
tests/integration/export_test.go Updated TestExportFiles to count .pb files in subdirectories, improving accuracy in file detection.

Poem

In the burrow of code, where the rabbits play,
New paths and names hop in with glee today.
Files find their homes, neat and tidy,
With every export, the code feels more sprightly!
Hooray for changes, let’s celebrate right,
In the world of exports, everything's bright! 🐰✨


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

github-actions bot commented Aug 6, 2024

New Coverage 47.6% of statements
Patch Coverage 46.7% of changed statements (14/30)

Coverage provided by /~https://github.com/seriousben/go-patch-cover-action

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: 1

Outside diff range, codebase verification and nitpick comments (3)
tests/integration/export_test.go (1)

87-98: Ensure robustness in nested directory handling.

The added code correctly handles nested directories. However, consider adding comments for clarity and improving readability.

    for _, entry := range entries {
        if entry.IsDir() {
+           // Handle nested directories
            files, err := os.ReadDir(filepath.Join(exportPath, entry.Name()))
            require.NoError(t, err)
            for _, file := range files {
                if filepath.Ext(file.Name()) == ".pb" {
                    foundPbFiles++
                }
            }
        } else {
            if filepath.Ext(entry.Name()) == ".pb" {
                foundPbFiles++
            }
        }
    }
core/block/export/export.go (2)

58-65: Add comments for new directory constants.

Adding comments to explain the purpose of each directory constant will improve code readability and maintainability.

const (
	// Temporary file name for backups
	tempFileName = "temp_anytype_backup"
	// Directory for space-related files
	spaceDirectory = "spaces"
	// Directory for type-related files
	typesDirectory = "types"
	// Directory for object-related files
	objectsDirectory = "objects"
	// Directory for relation-related files
	relationsDirectory = "relations"
	// Directory for relation options-related files
	relationsOptionsDirectory = "relationsOptions"
	// Directory for template-related files
	templatesDirectory = "templates"
	// Directory for file objects
	filesObjects = "filesObjects"
)

538-553: Ensure all block types are handled in provideFileDirectory.

The following SmartBlockType values are not handled in the provideFileDirectory method:

  • SmartBlockTypeAccountOld
  • SmartBlockTypePage
  • SmartBlockTypeProfilePage
  • SmartBlockTypeHome
  • SmartBlockTypeArchive
  • SmartBlockTypeWidget

Please review and update the provideFileDirectory method to handle these additional SmartBlockType values if necessary.

Analysis chain

Ensure all block types are handled in provideFileDirectory.

The switch-case structure should handle all possible smartblock.SmartBlockType values. Verify that no block types are missed.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all possible `smartblock.SmartBlockType` values are handled in `provideFileDirectory`.

# Test: Search for the `smartblock.SmartBlockType` enum definition. Expect: All enum values are handled in the switch-case.
rg --type go -A 10 $'type SmartBlockType'

Length of output: 2886

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a8ed9f6 and 9cf7e4e.

Files selected for processing (4)
  • core/block/export/export.go (3 hunks)
  • core/block/export/export_test.go (2 hunks)
  • core/block/export/writer.go (1 hunks)
  • tests/integration/export_test.go (1 hunks)
Additional comments not posted (2)
core/block/export/export_test.go (1)

501-564: Comprehensive test coverage for provideFileName method.

The new test function Test_provideFileName provides thorough validation for the provideFileName method. Ensure that all edge cases are covered.

core/block/export/export.go (1)

528-537: Ensure all calls to provideFileName include the new parameter.

The method signature has been updated to include blockType. Verify that all calls to this method have been updated accordingly.

Verification successful

All calls to provideFileName include the new parameter.

The verification confirms that the method signature update has been appropriately reflected in all instances where provideFileName is called.

  • core/block/export/export_test.go
  • core/block/export/export.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all calls to `provideFileName` include the new parameter.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type go -A 1 $'provideFileName('

Length of output: 121


Script:

#!/bin/bash
# Description: Verify all calls to `provideFileName` include the new parameter.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type go -A 1 'provideFileName\('

Length of output: 1950

Comment on lines 61 to 67
dir := filepath.Dir(filename)
if dir != "" {
err = os.MkdirAll(filepath.Join(d.path, dir), 0700)
if err != nil {
return err
}
}
Copy link

Choose a reason for hiding this comment

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

Ensure proper error handling for directory creation.

The added code correctly checks for a non-empty directory and attempts to create it. However, consider logging the error for better traceability.

    if dir != "" {
        err = os.MkdirAll(filepath.Join(d.path, dir), 0700)
        if err != nil {
+           // Log the error for better traceability
+           fmt.Printf("Failed to create directory %s: %v\n", filepath.Join(d.path, dir), err)
            return err
        }
    }
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.

Suggested change
dir := filepath.Dir(filename)
if dir != "" {
err = os.MkdirAll(filepath.Join(d.path, dir), 0700)
if err != nil {
return err
}
}
dir := filepath.Dir(filename)
if dir != "" {
err = os.MkdirAll(filepath.Join(d.path, dir), 0700)
if err != nil {
// Log the error for better traceability
fmt.Printf("Failed to create directory %s: %v\n", filepath.Join(d.path, dir), err)
return err
}
}

@@ -58,6 +58,13 @@ func (d *dirWriter) Path() string {
}

func (d *dirWriter) WriteFile(filename string, r io.Reader, lastModifiedDate int64) (err error) {
dir := filepath.Dir(filename)
if dir != "" {
Copy link
Contributor

Choose a reason for hiding this comment

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

What is the logic here, dir always returns nonempty string, for example fmt.Println(filepath.Dir("x.go")) == ".", you cannot create "." as a directory, it will return file exists. How does it work?

filename := docID + conv.Ext()
func (e *export) provideFileName(docID, spaceId string, conv converter.Converter, st *state.State, blockType smartblock.SmartBlockType) string {
dir := e.provideFileDirectory(blockType)
filename := filepath.Join(dir, docID+conv.Ext())
Copy link
Contributor

Choose a reason for hiding this comment

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

I guess we decided to use Id everywhere instead of ID

if spaceId == "" {
spaceId := pbtypes.GetString(st.LocalDetails(), bundle.RelationKeySpaceId.String())
filename = filepath.Join(spaceDirectory, spaceId, filename)
}
return filename
}

func (e *export) provideFileDirectory(blockType smartblock.SmartBlockType) string {
Copy link
Contributor

Choose a reason for hiding this comment

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

call it just fileDirectory maybe? and then fileName?

filename := docID + conv.Ext()
func (e *export) provideFileName(docID, spaceId string, conv converter.Converter, st *state.State, blockType smartblock.SmartBlockType) string {
dir := e.provideFileDirectory(blockType)
filename := filepath.Join(dir, docID+conv.Ext())
if spaceId == "" {
spaceId := pbtypes.GetString(st.LocalDetails(), bundle.RelationKeySpaceId.String())
Copy link
Contributor

Choose a reason for hiding this comment

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

Can it be the case that spaceId is nil? What happens here, why if spaceId == "" we do something completely different? Maybe It shouldn't be inside this function? Can you explain please?

Copy link
Member Author

Choose a reason for hiding this comment

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

It can be empty, if user want to export all spaces. We build file directory based on this value, so I guess it makes sense to check it here 🧐

Signed-off-by: AnastasiaShemyakinskaya <shem98a@mail.ru>
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9cf7e4e and 669c280.

Files selected for processing (2)
  • core/block/export/export.go (4 hunks)
  • core/block/export/writer.go (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • core/block/export/export.go
  • core/block/export/writer.go

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 669c280 and 533f2ec.

Files selected for processing (2)
  • core/block/export/export.go (5 hunks)
  • core/block/export/export_test.go (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • core/block/export/export_test.go
Additional comments not posted (6)
core/block/export/export.go (6)

470-470: Parameter naming change is consistent.

The change from docID to docId aligns with typical Go naming conventions.


529-531: Directory determination logic is efficient.

The use of provideFileDirectory to determine the directory based on blockType is efficient and improves file organization.


539-554: Switch-case structure for directory paths is comprehensive.

The provideFileDirectory function uses a switch-case structure to determine directory paths based on blockType. The cases seem comprehensive and well-structured.


Line range hint 516-524:
Markdown name generation logic is consistent.

The logic for generating markdown file names is consistent with the overall file naming strategy.


58-65: Ensure naming consistency for constants.

The naming of constants is consistent with the purpose of categorizing exported files. However, consider aligning with existing naming conventions if any discrepancies exist.

Verification successful

Constants are consistently named and used appropriately.

The constants for directory paths are used consistently across the codebase, particularly in constructing file paths and in test assertions. Their naming is clear and descriptive, aligning well with their intended purpose. No discrepancies were found.

  • Files Involved:
    • core/block/export/export.go
    • core/block/export/export_test.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage and consistency of newly introduced constants in the codebase.

# Test: Search for the usage of each constant. Expect: Consistent naming and usage across the codebase.
rg --type go 'tempFileName|spaceDirectory|typesDirectory|objectsDirectory|relationsDirectory|relationsOptionsDirectory|templatesDirectory|filesObjects'

Length of output: 2225


Line range hint 289-297:
Object retrieval logic is sound.

The logic for retrieving objects by IDs, including nested and file options, appears to be sound.

Consider verifying edge cases where includeNested and includeFiles might affect performance or correctness.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 533f2ec and b4f8757.

Files selected for processing (1)
  • core/block/export/export.go (4 hunks)
Additional comments not posted (5)
core/block/export/export.go (5)

58-65: Review the addition of directory constants.

The addition of directory constants (typesDirectory, objectsDirectory, etc.) improves the organization of exported files. These constants provide a clear and maintainable way to manage directory paths.


Line range hint 470-506:
LGTM! Consistent naming and improved filename generation.

The changes in parameter naming and the use of makeFileName enhance consistency and maintainability.


516-524: LGTM! Improved readability with parameter renaming.

The parameter renaming in makeMarkdownName enhances readability and aligns with Go naming conventions.


530-533: LGTM! Enhanced file organization with block type.

The use of blockType to determine directory paths improves file organization and flexibility in the export functionality.


541-556: LGTM! Improved modularity with provideFileDirectory.

The provideFileDirectory function centralizes directory path logic, enhancing modularity and maintainability.

@AnastasiaShemyakinskaya AnastasiaShemyakinskaya merged commit 5acb29e into main Aug 13, 2024
5 checks passed
@AnastasiaShemyakinskaya AnastasiaShemyakinskaya deleted the go-2746-export-structure branch August 13, 2024 13:02
@github-actions github-actions bot locked and limited conversation to collaborators Aug 13, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants