ronantakizawa/codereview-bench huggingface dataset:
Repository: maaslalani/slides
File: internal/navigation/navigation.go (Go)

Code before:
package navigation

import (
	"strconv"
)

type repeatableFunction func(slide, totalSlides int) int

// State represents the current buffer, current slide, and true if virtual text
// should be cleared.
type State struct {
	Buffer string
	Slide int
	ClearVirtualText bool
}

// Navigate receives the current State and keyPress, and returns the new State.
func Navigate(currentState State, keyPress string, numSlides int) State {
	// Implementation

	switch keyPress {
	case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
		newBuffer := keyPress

		if bufferIsNumeric(currentState.Buffer) {
			newBuffer = currentState.Buffer + keyPress
		}

		return State{
			Buffer:           newBuffer,
			Slide:            currentState.Slide,
			ClearVirtualText: false,
		}
	case "g":
		switch currentState.Buffer {
		case "g":
			return State {
				Buffer: "",
				Slide: navigateFirst(),

Review comment (suggestion):
I haven't thought about this too much, but do we need `ClearVirtualText`? This value could be inferred as `true` if Navigate returns a page other than the current page.

Code after:
package navigation

import (
	"strconv"
)

type repeatableFunction func(slide, totalSlides int) int

// State represents the current buffer, current slide, and true if virtual text
// should be cleared.
type State struct {
	Buffer    string
	Slide     int
	NumSlides int
}

// Navigate receives the current State and keyPress, and returns the new State.
func Navigate(currentState State, keyPress string) State {
	switch keyPress {
	case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
		newBuffer := keyPress

		if bufferIsNumeric(currentState.Buffer) {
			newBuffer = currentState.Buffer + keyPress
		}

		return State{
			Buffer:    newBuffer,
			Slide:     currentState.Slide,
			NumSlides: currentState.NumSlides,
		}
	case "g":
		switch currentState.Buffer {
		case "g":
			return State {
				Buffer: "",
				Slide: navigateFirst(),
				NumSlides: currentState.NumSlides,
			}
Repository: maaslalani/slides
File: internal/navigation/navigation.go (Go)

Code before:
		case "g":
			return State {
				Buffer: "",
				Slide: navigateFirst(),
				ClearVirtualText: false,
			}
		default:
			return State {
				Buffer: "g",
				Slide: currentState.Slide,
				ClearVirtualText: false,
			}
		}
	case "G":
		if bufferIsNumeric(currentState.Buffer) {
			return State {
				Buffer: "",
				Slide: navigateSlide(currentState.Buffer, numSlides),
				ClearVirtualText: false,
			}
		} else {
			return State {
				Buffer: "",
				Slide: navigateLast(numSlides),
				ClearVirtualText: false,
			}
		}
	case " ", "down", "j", "right", "l", "enter", "n":
		return State {
			Buffer: "",
			Slide: navigateNext(currentState.Buffer, currentState.Slide, numSlides),
			ClearVirtualText: true,
		}
	case "up", "k", "left", "h", "p":
		return State{
			Buffer: "",
			Slide:  navigatePrevious(currentState.Buffer, currentState.Slide, numSlides),
			ClearVirtualText: true,
		}
	default:
		return State {
			Buffer: "",
			Slide: currentState.Slide,
			ClearVirtualText: false,
		}
	}
}

func bufferIsNumeric(buffer string) bool {
	_, err := strconv.Atoi(buffer)
	return err == nil

Review comment (suggestion):
This could be simplified if you conditionally set the `Slide` value based on if the buffer is numeric and then return the struct with a slide variable since the other two are the same.

Code after:
				Buffer: "",
				Slide: navigateFirst(),
				NumSlides: currentState.NumSlides,
			}
		default:
			return State {
				Buffer: "g",
				Slide: currentState.Slide,
				NumSlides: currentState.NumSlides,
			}
		}
	case "G":
		targetSlide := navigateLast(currentState.NumSlides)
		if bufferIsNumeric(currentState.Buffer) {
			targetSlide = navigateSlide(currentState.Buffer, currentState.NumSlides)
		}

		return State {
			Buffer: "",
			Slide: targetSlide,
			NumSlides: currentState.NumSlides,
		}
	case " ", "down", "j", "right", "l", "enter", "n":
		return State {
			Buffer: "",
			Slide: navigateNext(currentState),
			NumSlides: currentState.NumSlides,
		}
	case "up", "k", "left", "h", "p":
		return State{
			Buffer: "",
			Slide:  navigatePrevious(currentState),
			NumSlides: currentState.NumSlides,
		}
	default:
		return State {
			Buffer: "",
			Slide: currentState.Slide,
			NumSlides: currentState.NumSlides,
		}
	}
}

func bufferIsNumeric(buffer string) bool {
	_, err := strconv.Atoi(buffer)
	return err == nil
}

func navigateFirst() int {
	return 0
}
Repository: maaslalani/slides
File: internal/model/model.go (Go)

Code before:
				if m.search.Buffer != "" {
					m.search.Execute(&m)
				} else {
					m.search.Cancel()
				}

			} else if msg.Type == tea.KeyBackspace {
				// delete last char from buffer
				m.search.Delete()

			} else if msg.Type == tea.KeyCtrlC || msg.Type == tea.KeyEscape {
				// quit command mode
				m.search.Cancel()
			}
			return m, nil
		}

		switch keyPress {
		case "/":
			// Begin search
			m.search.Begin()
			return m, nil
		case "ctrl+n":
			// Go to next occurrence
			m.search.Execute(&m)
		case "ctrl+e":
			// Run code blocks
			blocks, err := code.Parse(m.Slides[m.Page])
			if err != nil {
				// We couldn't parse the code block on the screen
				m.VirtualText = "\n" + err.Error()
				return m, nil
			}
			var outs []string
			for _, block := range blocks {
				res := code.Execute(block)
				outs = append(outs, res.Out)
			}
			m.VirtualText = strings.Join(outs, "\n")
		case "ctrl+c", "q":
			return m, tea.Quit
		default:
			newState := navigation.Navigate(navigation.State{
				Buffer:      m.buffer,
				Page:        m.Page,
				TotalSlides: len(m.Slides),
			}, keyPress)
			if newState.Page != m.Page {
				m.VirtualText = ""
			}
			m.buffer, m.Page = newState.Buffer, newState.Page

Review comment (suggestion):
My muscle memory is considering making this shortcut simply `n` 😄 

Code after:
			case tea.KeyEnter:
				// execute current buffer
				if m.search.Query != "" {
					m.search.Execute(&m)
				} else {
					m.search.Done()
				}

			case tea.KeyBackspace:
				// delete last char from buffer
				m.search.Delete()

			case tea.KeyCtrlC, tea.KeyEscape:
				// quit command mode
				m.search.Query = ""
				m.search.Done()
			}
			return m, nil
		}

		switch keyPress {
		case "/":
			// Begin search
			m.search.Begin()
			return m, nil
		case "ctrl+n":
			// Go to next occurrence
			m.search.Execute(&m)
		case "ctrl+e":
			// Run code blocks
			blocks, err := code.Parse(m.Slides[m.Page])
			if err != nil {
				// We couldn't parse the code block on the screen
				m.VirtualText = "\n" + err.Error()
				return m, nil
			}
			var outs []string
			for _, block := range blocks {
				res := code.Execute(block)
				outs = append(outs, res.Out)
			}
			m.VirtualText = strings.Join(outs, "\n")
		case "ctrl+c", "q":
			return m, tea.Quit
		default:
			newState := navigation.Navigate(navigation.State{
				Buffer:      m.buffer,
				Page:        m.Page,
				TotalSlides: len(m.Slides),
			}, keyPress)
			if newState.Page != m.Page {
Repository: maaslalani/slides
File: internal/model/model.go (Go)

Code before:
			fileInfo = newFileInfo
			_ = m.Load()
			if m.Page >= len(m.Slides) {
				m.Page = len(m.Slides) - 1
			}
		}
		return m, fileWatchCmd()
	}
	return m, nil
}

func (m Model) View() string {
	r, _ := glamour.NewTermRenderer(m.Theme, glamour.WithWordWrap(m.viewport.Width))
	slide := m.Slides[m.Page]
	slide, err := r.Render(slide)
	slide += m.VirtualText
	if err != nil {
		slide = fmt.Sprintf("Error: Could not render markdown! (%v)", err)
	}
	slide = styles.Slide.Render(slide)

	var left string
	if m.search.Active {
		// render search bar
		buf, sType := m.search.GetBufType()
		left = styles.ActionStatus.Render(fmt.Sprintf("[%s] 🔍: '%s'", sType.Desc, buf))
	} else {
		// render author and date
		left = styles.Author.Render(m.Author) + styles.Date.Render(m.Date)
	}

	right := styles.Page.Render(m.paging())
	status := styles.Status.Render(styles.JoinHorizontal(left, right, m.viewport.Width))
	return styles.JoinVertical(slide, status, m.viewport.Height)
}

func (m *Model) paging() string {
	switch strings.Count(m.Paging, "%d") {
	case 2:
		return fmt.Sprintf(m.Paging, m.Page+1, len(m.Slides))
	case 1:
		return fmt.Sprintf(m.Paging, m.Page+1)
	default:
		return m.Paging
	}
}

func readFile(path string) (string, error) {
	s, err := os.Stat(path)
	if err != nil {
		return "", errors.New("could not read file")

Review comment (suggestion):
Let's make this search bar a little more minimalistic like Vim. We should only see a `/` and the search term, nothing else.

Code after:
	case fileWatchMsg:
		newFileInfo, err := os.Stat(m.FileName)
		if err == nil && newFileInfo.ModTime() != fileInfo.ModTime() {
			fileInfo = newFileInfo
			_ = m.Load()
			if m.Page >= len(m.Slides) {
				m.Page = len(m.Slides) - 1
			}
		}
		return m, fileWatchCmd()
	}
	return m, nil
}

func (m Model) View() string {
	r, _ := glamour.NewTermRenderer(m.Theme, glamour.WithWordWrap(m.viewport.Width))
	slide := m.Slides[m.Page]
	slide, err := r.Render(slide)
	slide += m.VirtualText
	if err != nil {
		slide = fmt.Sprintf("Error: Could not render markdown! (%v)", err)
	}
	slide = styles.Slide.Render(slide)

	var left string
	if m.search.Active {
		// render search bar
		left = styles.ActionStatus.Render(fmt.Sprintf("/%s", m.search.Query))
	} else {
		// render author and date
		left = styles.Author.Render(m.Author) + styles.Date.Render(m.Date)
	}

	right := styles.Page.Render(m.paging())
	status := styles.Status.Render(styles.JoinHorizontal(left, right, m.viewport.Width))
	return styles.JoinVertical(slide, status, m.viewport.Height)
}

func (m *Model) paging() string {
	switch strings.Count(m.Paging, "%d") {
	case 2:
		return fmt.Sprintf(m.Paging, m.Page+1, len(m.Slides))
	case 1:
		return fmt.Sprintf(m.Paging, m.Page+1)
	default:
		return m.Paging
	}
}

func readFile(path string) (string, error) {
	s, err := os.Stat(path)
Repository: maaslalani/slides
File: internal/model/model.go (Go)

Code before:
	if err != nil {
		return "", err
	}

	if stat.Mode()&os.ModeNamedPipe == 0 && stat.Size() == 0 {
		return "", errors.New("no slides provided")
	}

	reader := bufio.NewReader(os.Stdin)
	var b strings.Builder

	for {
		r, _, err := reader.ReadRune()
		if err != nil && err == io.EOF {
			break
		}
		_, err = b.WriteRune(r)
		if err != nil {
			return "", err
		}
	}

	return b.String(), nil
}

func (m *Model) GetPage() int {
	return m.Page
}

func (m *Model) SetPage(page int) {
	m.Page = page
}

func (m *Model) GetSlides() []string {
	return m.Slides
}


Review comment (suggestion):
Nit: No `Get` prefix this function should be `Page()` or `CurrentPage()` up to you.

Reasoning for not having `Get` prefixes: https://golang.org/doc/effective_go#Getters

Code after:
func readStdin() (string, error) {
	stat, err := os.Stdin.Stat()
	if err != nil {
		return "", err
	}

	if stat.Mode()&os.ModeNamedPipe == 0 && stat.Size() == 0 {
		return "", errors.New("no slides provided")
	}

	reader := bufio.NewReader(os.Stdin)
	var b strings.Builder

	for {
		r, _, err := reader.ReadRune()
		if err != nil && err == io.EOF {
			break
		}
		_, err = b.WriteRune(r)
		if err != nil {
			return "", err
		}
	}

	return b.String(), nil
}

func (m *Model) CurrentPage() int {
	return m.Page
}

func (m *Model) SetPage(page int) {
	m.Page = page
}

func (m *Model) Pages() []string {
	return m.Slides
}
Repository: maaslalani/slides
File: internal/navigation/search.go (Go)

Code before:
package navigation

import (
	"regexp"
	"strings"
)

type searchFunc func(content string) bool

type searchType struct {
	Desc string
	fn   func(buf string) searchFunc
}

var SearchTypes = map[rune]*searchType{
	// header search
	// Search only in headings (case insensitive)
	0: {
		Desc: "header",
		fn: func(buf string) searchFunc {
			return func(content string) bool {
				return hasHeader(extractHeaders(content), buf) != ""
			}
		},
	},
	// full-text search
	// Search for any text on the presentation, including paragraphs, but also code blocks.
	// (case insensitive)
	'*': {
		Desc: "full-text-ci",
		fn: func(buf string) searchFunc {
			return func(content string) bool {
				return strings.Contains(strings.ToLower(content), strings.ToLower(buf))
			}
		},
	},
	// full-text search
	// Search for any text on the presentation, including paragraphs, but also code blocks.
	// (case sensitive)
	'^': {

Review comment (suggestion):
Considering not having search types, see comment above. We really only need regex, since case sensitivity can be passed as a (regex) flag. It would also then be possible to pass header search as a flag as well: `/headersearch/h`.

Code after:
package navigation

import (
	"regexp"
	"strings"
)

// Model is an interface for models.model, so that cycle imports are avoided
type Model interface {
	CurrentPage() int
	SetPage(page int)
	Pages() []string
}

// Search represents the current search
type Search struct {
	// Active - Show search bar instead of author and date?
	// Store keystrokes in Query?
	Active bool
	// Query stores the current "search term"
	Query string
}

// Mark Search as
// Done - Do not delete search buffer
// This is useful if, for example, you want to jump to the next result
// and you therefore still need the buffer
func (s *Search) Done() {
	s.Active = false
}

// Begin a new search (deletes old buffer)
func (s *Search) Begin() {
	s.Active = true
	s.Query = ""
}

// Write a keystroke to the buffer
func (s *Search) Write(key string) {
	s.Query += key
Repository: maaslalani/slides
File: internal/model/model.go (Go)

Code before:
			m.Search.SearchTextInput.Focus()
			return m, nil
		case "ctrl+n":
			// Go to next occurrence
			m.Search.Execute(&m)
		case "ctrl+e":
			// Run code blocks
			blocks, err := code.Parse(m.Slides[m.Page])
			if err != nil {
				// We couldn't parse the code block on the screen
				m.VirtualText = "\n" + err.Error()
				return m, nil
			}
			var outs []string
			for _, block := range blocks {
				res := code.Execute(block)
				outs = append(outs, res.Out)
			}
			m.VirtualText = strings.Join(outs, "\n")
		case "y":
			blocks, err := code.Parse(m.Slides[m.Page])
			if err != nil {
				return m, nil
			}
			for _, b := range blocks {
				clipboard.WriteAll(b.Code)
			}
			return m, nil
		case "ctrl+c", "q":
			return m, tea.Quit
		default:
			newState := navigation.Navigate(navigation.State{
				Buffer:      m.buffer,
				Page:        m.Page,
				TotalSlides: len(m.Slides),
			}, keyPress)
			m.buffer = newState.Buffer
			m.SetPage(newState.Page)
		}

	case fileWatchMsg:
		newFileInfo, err := os.Stat(m.FileName)
		if err == nil && newFileInfo.ModTime() != fileInfo.ModTime() {
			fileInfo = newFileInfo
			_ = m.Load()
			if m.Page >= len(m.Slides) {
				m.Page = len(m.Slides) - 1
			}
		}
		return m, fileWatchCmd()
	}

Review comment (suggestion):
```suggestion
				_ = clipboard.WriteAll(b.Code)
```

Code after:
			m.Search.SearchTextInput.Focus()
			return m, nil
		case "ctrl+n":
			// Go to next occurrence
			m.Search.Execute(&m)
		case "ctrl+e":
			// Run code blocks
			blocks, err := code.Parse(m.Slides[m.Page])
			if err != nil {
				// We couldn't parse the code block on the screen
				m.VirtualText = "\n" + err.Error()
				return m, nil
			}
			var outs []string
			for _, block := range blocks {
				res := code.Execute(block)
				outs = append(outs, res.Out)
			}
			m.VirtualText = strings.Join(outs, "\n")
		case "y":
			blocks, err := code.Parse(m.Slides[m.Page])
			if err != nil {
				return m, nil
			}
			for _, b := range blocks {
				_ = clipboard.WriteAll(b.Code)
			}
			return m, nil
		case "ctrl+c", "q":
			return m, tea.Quit
		default:
			newState := navigation.Navigate(navigation.State{
				Buffer:      m.buffer,
				Page:        m.Page,
				TotalSlides: len(m.Slides),
			}, keyPress)
			m.buffer = newState.Buffer
			m.SetPage(newState.Page)
		}

	case fileWatchMsg:
		newFileInfo, err := os.Stat(m.FileName)
		if err == nil && newFileInfo.ModTime() != fileInfo.ModTime() {
			fileInfo = newFileInfo
			_ = m.Load()
			if m.Page >= len(m.Slides) {
				m.Page = len(m.Slides) - 1
			}
		}
		return m, fileWatchCmd()
	}
Repository: mastra-ai/mastra
File: packages/cli/src/commands/init/utils.ts (TypeScript)

Code before:
  const cwd = process.cwd();
  const pkgJsonPath = path.join(cwd, 'package.json');

  try {
    await fs.access(pkgJsonPath);

    // Do nothing
  } catch {
    p.log.error(
      'No package.json file found in the current directory. Please run "npm init -y" to create one, or run "npx create-mastra@latest" to create a new Mastra project.',
    );

    process.exit(1);
  }
};

/**
 * Generate content for AGENTS.md file
 */
export function generateAgentsMarkdown({ skills, mcpServer }: { skills?: string[]; mcpServer?: Editor }): string {
  const hasSkills = skills && skills.length > 0;
  const hasMcp = !!mcpServer;

  let content = `# AI Agents Guide

This guide helps AI agents work efficiently with this Mastra project.

## Quick Start

\`\`\`bash
# Install dependencies
npm install

# Run development server
npm run dev

# Build the project
npm run build
\`\`\`

## Project Structure

- \`src/mastra/\` - Main Mastra configuration and components
- \`src/mastra/agents/\` - AI agent definitions
- \`src/mastra/tools/\` - Tool implementations
- \`src/mastra/workflows/\` - Workflow definitions

`;

  // Add skills section if skills were installed
  if (hasSkills) {

Review comment (suggestion):
```suggestion
This document provides guidance for AI coding agents working in this repository.
```

Code after:
  const cwd = process.cwd();
  const pkgJsonPath = path.join(cwd, 'package.json');

  try {
    await fs.access(pkgJsonPath);

    // Do nothing
  } catch {
    p.log.error(
      'No package.json file found in the current directory. Please run "npm init -y" to create one, or run "npx create-mastra@latest" to create a new Mastra project.',
    );

    process.exit(1);
  }
};

/**
 * Generate content for AGENTS.md file
 */
export function generateAgentsMarkdown({ skills, mcpServer }: { skills?: string[]; mcpServer?: Editor }): string {
  const hasSkills = skills && skills.length > 0;
  const hasMcp = !!mcpServer;

  let content = `# AGENTS.md

This document provides guidance for AI coding agents working in this repository.

## Project Overview

This is a **Mastra** project written in TypeScript. Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.

## Commands

Use these commands to interact with the project.

### Installation

\`\`\`bash
npm install
\`\`\`

### Development

Start the Mastra Studio at localhost:4111 by running the \`dev\` script:

\`\`\`bash
npm run dev
\`\`\`

### Build
Repository: mastra-ai/mastra
File: packages/cli/src/commands/init/utils.ts (TypeScript)

Code before:
  try {
    await fs.access(pkgJsonPath);

    // Do nothing
  } catch {
    p.log.error(
      'No package.json file found in the current directory. Please run "npm init -y" to create one, or run "npx create-mastra@latest" to create a new Mastra project.',
    );

    process.exit(1);
  }
};

/**
 * Generate content for AGENTS.md file
 */
export function generateAgentsMarkdown({ skills, mcpServer }: { skills?: string[]; mcpServer?: Editor }): string {
  const hasSkills = skills && skills.length > 0;
  const hasMcp = !!mcpServer;

  let content = `# AI Agents Guide

This guide helps AI agents work efficiently with this Mastra project.

## Quick Start

\`\`\`bash
# Install dependencies
npm install

# Run development server
npm run dev

# Build the project
npm run build
\`\`\`

## Project Structure

- \`src/mastra/\` - Main Mastra configuration and components
- \`src/mastra/agents/\` - AI agent definitions
- \`src/mastra/tools/\` - Tool implementations
- \`src/mastra/workflows/\` - Workflow definitions

`;

  // Add skills section if skills were installed
  if (hasSkills) {
    content += `## Mastra Skills

Skills are modular capabilities that extend agent functionalities. They provide pre-built tools, integrations, and workflows that agents can leverage to accomplish tasks more effectively.

Review comment (suggestion):
```suggestion
## Project Overview

This is a **Mastra AI agent framework** project written in TypeScript. Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.
```

Code after:
  try {
    await fs.access(pkgJsonPath);

    // Do nothing
  } catch {
    p.log.error(
      'No package.json file found in the current directory. Please run "npm init -y" to create one, or run "npx create-mastra@latest" to create a new Mastra project.',
    );

    process.exit(1);
  }
};

/**
 * Generate content for AGENTS.md file
 */
export function generateAgentsMarkdown({ skills, mcpServer }: { skills?: string[]; mcpServer?: Editor }): string {
  const hasSkills = skills && skills.length > 0;
  const hasMcp = !!mcpServer;

  let content = `# AGENTS.md

This document provides guidance for AI coding agents working in this repository.

## Project Overview

This is a **Mastra** project written in TypeScript. Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.

## Commands

Use these commands to interact with the project.

### Installation

\`\`\`bash
npm install
\`\`\`

### Development

Start the Mastra Studio at localhost:4111 by running the \`dev\` script:

\`\`\`bash
npm run dev
\`\`\`

### Build

In order to build a production-ready server, run the \`build\` script:

\`\`\`bash