Skip to content

Conversation

cnlangzi
Copy link
Member

@cnlangzi cnlangzi commented Jan 14, 2025

Changed

Fixed

Added

Tests

Tasks to complete before merging PR:

  • Ensure unit tests are passing. If not run make unit-test to check for any regressions 📋
  • Ensure lint tests are passing. if not run make lint to check for any issues
  • Ensure codecov/patch is passing for changes.

Summary by Sourcery

Add support for text files as views, allowing them to be rendered directly by the application. Update the view engine to handle empty templates correctly, preventing errors during rendering.

New Features:

  • Added TextViewEngine and TextViewer to support rendering text files as views.

Tests:

  • Added tests for the new text view engine.

Copy link

sourcery-ai bot commented Jan 14, 2025

Reviewer's Guide by Sourcery

This pull request introduces support for text-based templates by adding a new TextViewEngine and TextViewer. It also includes updates to handle empty HTML templates and improves MIME type handling.

Sequence diagram for text template rendering process

sequenceDiagram
    participant C as Client
    participant A as App
    participant TV as TextViewer
    participant TT as TextTemplate

    C->>A: Request text template
    A->>TV: Render(w, r, data)
    TV->>TV: Set Content-Type header
    TV->>TT: Execute(buffer, data)
    TT-->>TV: Rendered content
    TV-->>A: Write to response
    A-->>C: Send response
Loading

Class diagram for new TextViewEngine and TextViewer components

classDiagram
    class TextViewEngine {
      -fsys fs.FS
      -app *App
      -templates map[string]*TextTemplate
      +Load(fsys fs.FS, app *App) error
      +FileChanged(fsys fs.FS, app *App, event fsnotify.Event) error
      -loadText(path string) error
      -loadTemplate(path string) *TextTemplate
    }
    class TextTemplate {
      -template *template.Template
      -name string
      -mime string
      -charset string
      +Load(fsys fs.FS) error
      +Reload(fsys fs.FS) error
      +Execute(wr io.Writer, data any) error
    }
    class TextViewer {
      -template *TextTemplate
      +MimeType() string
      +Render(w http.ResponseWriter, r *http.Request, data any) error
    }
    TextViewEngine --> TextTemplate : manages
    TextViewer --> TextTemplate : uses
    note for TextViewEngine "Handles text template loading and file watching"
    note for TextViewer "Renders text templates with proper MIME types"
Loading

File-Level Changes

Change Details Files
Added support for text templates.
  • Introduced TextViewEngine to handle text templates.
  • Created TextViewer to render text templates.
  • Added TextTemplate to manage template parsing and execution.
  • Implemented MIME type detection for text files.
  • Added tests for the new text template engine.
  • Updated go.mod and go.sum to reflect new dependencies
app.go
viewengine_text.go
viewengine_text_test.go
viewer_text.go
template_text.go
template_text_test.go
mime.go
mime_test.go
go.mod
go.sum
Improved handling of empty HTML templates.
  • Fixed an issue where empty HTML templates caused an error.
  • Added a test case for empty HTML templates
html_template.go
app_test.go
Enhanced MIME type handling in the Context.Accept method.
  • Improved parsing of the Accept header to handle more complex cases.
  • Added support for wildcard MIME types
context.go

Assessment against linked issues

Issue Objective Addressed Explanation
#19 Add TextViewEngine to support rendering text-based templates
#19 Add TextViewer to render text files as templates

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

deepsource-io bot commented Jan 14, 2025

Here's the code health analysis summary for commits 3a87b98..f0a9d5c. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource Go LogoGo✅ Success
🎯 1 occurence resolved
View Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

Copy link

codecov bot commented Jan 14, 2025

Codecov Report

Attention: Patch coverage is 92.62295% with 9 lines in your changes missing coverage. Please review.

Project coverage is 89.79%. Comparing base (3a87b98) to head (f0a9d5c).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
viewengine_text.go 89.83% 4 Missing and 2 partials ⚠️
viewer_text.go 76.92% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #23      +/-   ##
==========================================
+ Coverage   89.27%   89.79%   +0.52%     
==========================================
  Files          28       32       +4     
  Lines        1063     1176     +113     
==========================================
+ Hits          949     1056     +107     
- Misses         79       83       +4     
- Partials       35       37       +2     
Flag Coverage Δ
Unit-Tests 89.79% <92.62%> (+0.52%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟡 Security: 1 issue found
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@cnlangzi
Copy link
Member Author

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @cnlangzi - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟡 Testing: 1 issue found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -79,7 +79,7 @@ func (c *Context) View(items ...any) error {
mime := v.MimeType()
ok = false
for _, accept := range c.Accept() {
if mime == accept {
if mime == accept || mime == "*/*" || accept == "*/*" {
Copy link

Choose a reason for hiding this comment

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

suggestion: Consider reordering MIME type checks to prioritize exact matches

The current order could match wildcards before more specific MIME types. Consider checking exact matches first: if mime == accept || (accept == "*/*" || mime == "*/*")

Suggested change
if mime == accept || mime == "*/*" || accept == "*/*" {
if mime == accept || (mime == "*/*" || accept == "*/*") {

"github.com/yaitoo/xun/fsnotify"
)

func TestTextViewEngine(t *testing.T) {
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): Test cases for non-existent files.

Add a test case where the requested text file does not exist in the fsys. This verifies that the engine handles this scenario gracefully, perhaps by returning a 404 error or a default response.

Suggested implementation:

	fsys := fstest.MapFS{
		"text/sitemap.xml": {Data: []byte(`<?xml version="1.0" encoding="UTF-8"?>`)},
		"text/robots.txt":  {Data: []byte("User-agent: *")},
		"text/empty.md":    {},
	}

	mux := http.NewServeMux()
	srv := httptest.NewServer(mux)
	defer srv.Close()

	app := New(WithMux(mux), WithFsys(fsys))

	t.Run("non-existent file returns 404", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/text/nonexistent.txt", nil)
		w := httptest.NewRecorder()
		app.ServeHTTP(w, req)

		require.Equal(t, http.StatusNotFound, w.Code)
	})

The exact status code (404) assumes that's how your engine handles missing files. If your engine uses a different status code or handling mechanism for missing files, you'll need to adjust the expected status code in the test accordingly.

@cnlangzi cnlangzi merged commit 4f89ace into main Jan 14, 2025
7 checks passed
@cnlangzi cnlangzi deleted the feat/text branch January 14, 2025 08:13
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.

[feat]add TextViewEngine and TextViewer
1 participant