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

Programming exercises: Add Go programming language template #9751

Open
wants to merge 21 commits into
base: feature/programming-exercises/concat-nested-testsuite-names
Choose a base branch
from

Conversation

magaupp
Copy link
Contributor

@magaupp magaupp commented Nov 11, 2024

Checklist

General

Server

Changes affecting Programming Exercises

  • High priority: I tested all changes and their related features with all corresponding user types on a test server configured with the integrated lifecycle setup (LocalVC and LocalCI).
  • I tested all changes and their related features with all corresponding user types on a local server configured with LocalVC and Jenkins.

Motivation and Context

Go currently is on rank 12 of the PYPL Index and should be included as a relevant language for programming exercises.

Description

This PR adds Go as a programming exercise template. It uses the Strategy Pattern example as used in the other languages.
The tests use the standard testing package to be run with go test. The output is converted to JUnit XML using go-junit-report.

This PR also includes refactoring of client code for easy extensibility of package name verification.

Steps for Testing

Prerequisites:

  • 1 Instructor
  1. Navigate to the exercise creation page
  2. Select Go for the language
  3. Verify that only valid Go identifiers can be used for the package name
  4. Fill out all necessary fields correctly and generate the exercise
  5. Wait until the test results are available in the exercise details page
  6. Verify that the template result passes 0/8 tests without build failure
  7. Verify that the solution result passes 8/8 tests without build failure

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for the Go programming language across various components, including programming exercises, plagiarism detection, and continuous integration.
    • Introduced new Go-related templates and scripts for automated testing and exercise management.
  • Enhancements

    • Improved validation for package names and application names for Go and other languages.
    • Updated documentation to reflect new Go support and validation messages in multiple languages.
  • Bug Fixes

    • Refined error handling and validation logic related to programming exercises, ensuring better user guidance.
  • Chores

    • Updated localization files to include Go-specific validation messages in German and English.

@github-actions github-actions bot added server Pull requests that update Java code. (Added Automatically!) client Pull requests that update TypeScript code. (Added Automatically!) config-change Pull requests that change the config in a way that they require a deployment via Ansible. template plagiarism Pull requests that affect the corresponding module programming Pull requests that affect the corresponding module labels Nov 11, 2024
@magaupp magaupp force-pushed the feature/programming-exercises/go-template branch 5 times, most recently from 6e3ce88 to 1572313 Compare November 24, 2024 17:40
@github-actions github-actions bot added tests documentation buildagent Pull requests that affect the corresponding module labels Nov 24, 2024
@magaupp magaupp changed the base branch from develop to feature/programming-exercises/concat-nested-testsuite-names November 24, 2024 17:42
@magaupp magaupp temporarily deployed to artemis-test4.artemis.cit.tum.de November 24, 2024 17:52 — with GitHub Actions Inactive
@magaupp magaupp requested a review from a team as a code owner November 26, 2024 17:59
@magaupp
Copy link
Contributor Author

magaupp commented Nov 26, 2024

@coderabbitai review

Copy link

coderabbitai bot commented Nov 26, 2024

Walkthrough

The changes in this pull request primarily focus on integrating support for the Go programming language across various components of the project. Key modifications include adding Go as a dependency in build.gradle, updating documentation to reflect Go's support, and implementing Go-specific logic in multiple service classes. Additionally, new Go-related files for sorting algorithms and testing frameworks have been introduced, enhancing the project's capabilities for Go submissions. Overall, these changes establish a comprehensive framework for handling Go programming exercises within the existing system.

Changes

File Change Summary
build.gradle Added dependency: implementation "de.jplag:golang:${jplag_version}" for Go language support.
docs/user/exercises/programming-exercise-features.inc Updated to include Go in programming language support tables.
src/main/java/de/tum/cit/aet/artemis/plagiarism/service/ProgrammingPlagiarismDetectionService.java Added support for Go in plagiarism detection logic.
src/main/java/de/tum/cit/aet/artemis/programming/domain/ProgrammingLanguage.java Updated ENABLED_LANGUAGES to include GO.
src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseRepositoryService.java Added case for handling Go in replacePlaceholders method.
src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseService.java Introduced regex patterns for Go package names and updated validation logic.
src/main/java/de/tum/cit/aet/artemis/programming/service/TemplateUpgradePolicyService.java Updated to support Go in upgrade service logic.
src/main/java/de/tum/cit/aet/artemis/programming/service/ci/ContinuousIntegrationService.java Added Go to repository checkout paths.
src/main/java/de/tum/cit/aet/artemis/programming/service/jenkins/JenkinsProgrammingLanguageFeatureService.java Added Go language features in Jenkins service.
src/main/java/de/tum/cit/aet/artemis/programming/service/jenkins/build_plan/JenkinsBuildPlanService.java Updated build plan logic to include Go.
src/main/java/de/tum/cit/aet/artemis/programming/service/localci/LocalCIProgrammingLanguageFeatureService.java Added Go language features in Local CI service.
src/main/resources/templates/aeolus/go/default.sh Introduced a new shell script for Go testing.
src/main/resources/templates/go/exercise/*.go Added multiple Go files for sorting algorithms and related functionality.
src/main/resources/templates/go/readme Structured exercise for implementing sorting algorithms using Strategy Pattern.
src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseFactory.java Updated logic for setting package names based on programming language.
src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseTestService.java Modified package name handling and validation logic.
src/test/javascript/spec/component/programming-exercise/programming-exercise-update.component.spec.ts Updated tests to use new constants for package name patterns.
src/test/javascript/spec/component/programming-exercise/update-components/programming-exercise-creation-config-mock.ts Removed unused property appNamePatternForSwift.

Possibly related PRs

Suggested labels

small, bugfix

Suggested reviewers

  • krusche
  • EneaGore
  • JohannesStoehr
  • b-fein
  • ole-ve

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

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

🧹 Outside diff range and nitpick comments (40)
src/main/resources/templates/go/exercise/context.go (3)

3-3: Add documentation for the Context type

Consider adding a documentation comment explaining the purpose of the Context type and its role in the Strategy Pattern implementation. This will help students understand the design pattern better.

+// Context represents the execution context for sorting algorithms.
+// It is part of the Strategy Pattern implementation and manages the sorting process.
 type Context struct{}

5-7: Enhance the panic message to be more instructive

The current panic message could be more helpful for students. Consider providing a more detailed message that guides them on what needs to be implemented.

 func NewContext() *Context {
-	panic("not implemented")
+	panic("TODO: Implement NewContext() to initialize and return a new Context instance")
 }

1-7: Consider adding package documentation

Since this is a teaching template implementing the Strategy Pattern, it would be valuable to add package-level documentation explaining the overall design pattern and how the various components (Context, Policy, SortStrategy) interact.

+// Package ${packageName} implements the Strategy Pattern for sorting algorithms.
+// It demonstrates how to separate sorting algorithms from their execution context,
+// allowing for flexible runtime selection of different sorting strategies.
 package ${packageName}
src/main/resources/templates/go/exercise/mergesort.go (1)

1-7: Consider adding test scaffolding

Since this is an exercise template, it would be beneficial to include:

  1. Test file structure
  2. Example test cases
  3. Benchmarking setup

Would you like me to generate a companion test file with the recommended structure?

src/main/resources/templates/go/exercise/bubblesort.go (1)

5-7: Add constructor documentation

The constructor should have documentation explaining its purpose and return value.

Consider adding:

+// NewBubbleSort creates a new bubble sort strategy instance
 func NewBubbleSort() *BubbleSort {
     panic("not implemented")
 }
src/main/resources/templates/go/exercise/policy.go (1)

1-7: Add documentation comments following Go conventions

To improve code maintainability and follow Go best practices, add documentation comments for the package, type, and methods.

+// Package ${packageName} implements the Strategy Pattern for sorting algorithms
package ${packageName}

const datesSizeThreshold = 10

+// Policy determines which sorting algorithm to use based on the input size
type Policy struct {
    context *Context
}

+// NewPolicy creates a new Policy with the given Context
func NewPolicy(context *Context) *Policy {
    return &Policy{
        context: context,
    }
}
src/main/resources/templates/go/solution/bubblesort.go (2)

5-5: Add documentation comment for the BubbleSort type.

Consider adding a documentation comment to describe the type's purpose and behavior.

+// BubbleSort implements bubble sort algorithm for time.Time slices
 type BubbleSort struct{}

7-9: Add documentation and consider simpler constructor.

The constructor follows Go conventions but could be improved.

+// NewBubbleSort creates a new bubble sort instance
 func NewBubbleSort() *BubbleSort {
-    return new(BubbleSort)
+    return &BubbleSort{}
 }
src/main/resources/templates/go/solution/policy.go (3)

3-5: Add documentation for the Policy struct

Consider adding a documentation comment for the Policy struct explaining its role in the strategy pattern implementation.

+// Policy determines and configures the appropriate sorting algorithm based on the input size.
+// It implements the strategy pattern by dynamically selecting between merge sort and bubble sort.
 type Policy struct {
 	context *Context
 }

7-7: Improve constant documentation and naming

The threshold constant would benefit from documentation explaining why 10 was chosen as the cutoff point.

+// sortingStrategyThreshold defines the input size threshold (n=10) for choosing between
+// bubble sort (n ≤ 10, O(n²)) and merge sort (n > 10, O(n log n)).
-const datesSizeThreshold = 10
+const sortingStrategyThreshold = 10

13-20: Enhance Configure method documentation and error handling

The method would benefit from more detailed documentation and error handling for the sort algorithm creation.

-// Configure chooses a strategy depending on the number of date objects.
+// Configure selects an appropriate sorting strategy based on the input size.
+// For n ≤ 10 elements, it uses bubble sort due to its efficiency with small datasets
+// and simple implementation. For n > 10, it switches to merge sort to maintain
+// O(n log n) performance on larger datasets.
 func (p *Policy) Configure() {
-	if len(p.context.GetDates()) > datesSizeThreshold {
-		p.context.SetSortAlgorithm(NewMergeSort())
+	dates := p.context.GetDates()
+	if len(dates) > sortingStrategyThreshold {
+		p.context.SetSortAlgorithm(NewMergeSort())
 	} else {
 		p.context.SetSortAlgorithm(NewBubbleSort())
 	}
 }
src/main/resources/templates/go/solution/context.go (1)

10-12: Consider initializing the dates slice in the constructor

While the constructor follows Go naming conventions, initializing the dates slice would prevent potential nil panics.

 func NewContext() *Context {
-	return new(Context)
+	return &Context{
+		dates: make([]time.Time, 0),
+	}
 }
src/main/resources/templates/go/solution/mergesort.go (3)

5-9: Add explicit interface implementation declaration

Based on the AI summary, this type should implement the SortStrategy interface. Consider adding an explicit declaration to ensure interface compliance at compile-time.

+// Ensure MergeSort implements SortStrategy
+var _ SortStrategy = (*MergeSort)(nil)
+
 type MergeSort struct{}

16-26: Enhance function documentation

The function's documentation should be more descriptive about its behavior and complexity.

-// mergeSort recursively applies the MergeSort algorithm.
+// mergeSort recursively sorts the input slice using the merge sort algorithm.
+// Time complexity: O(n log n), Space complexity: O(n)
+// The function modifies the input slice in-place.
 func mergeSort(input []time.Time) {

28-57: Improve variable naming and documentation

The merge function could benefit from more descriptive variable names and detailed documentation.

-// merge merges two ranges within input defined from low to mid and from mid+1 to high.
+// merge combines two sorted sub-slices (input[0:mid] and input[mid:]) into a single sorted slice.
+// It uses a temporary slice to perform the merge operation.
+// Parameters:
+//   - input: the slice containing both sub-slices to be merged
+//   - mid: the index where the first sub-slice ends and the second begins
 func merge(input []time.Time, mid int) {
 	temp := make([]time.Time, len(input))
 
-	left, right, k := 0, mid, 0
+	leftIdx, rightIdx, mergeIdx := 0, mid, 0
 
-	for left < mid && right < len(input) {
-		if input[left].Before(input[right]) {
-			temp[k] = input[left]
-			left++
+	for leftIdx < mid && rightIdx < len(input) {
+		if input[leftIdx].Before(input[rightIdx]) {
+			temp[mergeIdx] = input[leftIdx]
+			leftIdx++
 		} else {
-			temp[k] = input[right]
-			right++
+			temp[mergeIdx] = input[rightIdx]
+			rightIdx++
 		}
-		k++
+		mergeIdx++
 	}
src/main/resources/templates/go/test/structural/structural_test.go (4)

10-23: Add interface documentation

The interfaces are well-designed but would benefit from documentation comments explaining their purpose and usage. Consider adding GoDoc comments for better code documentation.

Apply this diff to add documentation:

+// SortStrategy defines the interface for time-based sorting algorithms
 type SortStrategy interface {
 	PerformSort(input []time.Time)
 }

+// Context manages the sorting context including dates and algorithm selection
 type Context interface {
 	GetDates() []time.Time
 	SetDates(dates []time.Time)
 	GetSortAlgorithm() ${packageName}.SortStrategy
 	SetSortAlgorithm(strategy ${packageName}.SortStrategy)
 }

+// Policy defines the configuration behavior for sorting strategies
 type Policy interface {
 	Configure()
 }

25-55: Enhance test coverage with behavioral tests

While the structural tests verify interface implementation, consider adding behavioral tests to ensure the sorting algorithms work correctly.

Example test to add:

func TestBubbleSortBehavior(t *testing.T) {
    dates := []time.Time{
        time.Date(2023, 12, 3, 0, 0, 0, 0, time.UTC),
        time.Date(2023, 12, 1, 0, 0, 0, 0, time.UTC),
        time.Date(2023, 12, 2, 0, 0, 0, 0, time.UTC),
    }
    sorter := new(${packageName}.BubbleSort)
    sorter.PerformSort(dates)
    
    // Verify sorting
    for i := 1; i < len(dates); i++ {
        if dates[i].Before(dates[i-1]) {
            t.Errorf("Dates not properly sorted at index %d", i)
        }
    }
}

57-62: Enhance panic handler with more detailed error information

The panic handler could provide more context about where the panic occurred to aid in debugging.

Apply this diff to improve error reporting:

 // handlePanic fatally fails the test without terminating the test suite.
 func handlePanic(t *testing.T) {
 	if err := recover(); err != nil {
-		t.Fatal("panic:", err)
+		t.Fatalf("panic occurred during test execution: %v\nStack trace:\n%s", err, debug.Stack())
 	}
 }

Don't forget to add "runtime/debug" to the imports.


1-62: Consider implementing test helpers for common testing patterns

The current implementation provides a good foundation. Consider extracting common testing patterns into helper functions to promote code reuse across other Go template tests.

Some suggestions:

  1. Create a helper function for type assertion tests
  2. Implement a common date fixture generator
  3. Add a test suite setup function for shared test configuration

This will make the test suite more maintainable as more Go templates are added to the system.

src/main/resources/templates/jenkins/go/regularRuns/pipeline.groovy (2)

46-49: Enhance post-build task robustness

The current implementation might silently fail. Consider adding explicit checks and proper error handling.

Consider this more robust implementation:

-rm -rf results
-mkdir results
-cp "tests/test-results.xml" $WORKSPACE/results/ || true
-sed -i 's/[^[:print:]\t]/�/g' $WORKSPACE/results/*.xml || true
+rm -rf results
+mkdir -p results
+if [ -f "tests/test-results.xml" ]; then
+    cp "tests/test-results.xml" "$WORKSPACE/results/"
+    sed -i 's/[^[:print:]\t]/�/g' "$WORKSPACE/results/"*.xml
+else
+    echo "Warning: test-results.xml not found"
+    exit 1
+fi

17-21: Consider security improvements for shell operations

The script could benefit from additional security measures:

  1. Use of absolute paths where appropriate
  2. Proper quoting of variables
  3. Restricted permissions for created directories

Consider implementing these security improvements:

  1. Add set -euo pipefail at the beginning of shell scripts
  2. Use mktemp -d for temporary directory creation
  3. Add appropriate file permissions: mkdir -m 755 results

Also applies to: 45-50

src/main/resources/templates/go/exercise/client/client.go (3)

9-14: Enhance constant documentation with rationale.

While the constants are well-named, consider adding documentation explaining why these specific values were chosen. For example, why is the range 5-15 appropriate for this exercise?

 // Constants define iteration and random date generation bounds.
 const (
+	// Iterations defines how many times the sorting demonstration runs
 	Iterations    = 10
+	// RandomFloor defines the minimum number of dates to generate
 	RandomFloor   = 5
+	// RandomCeiling defines the maximum number of dates to generate
 	RandomCeiling = 15
 )

38-50: Consider making date range configurable and adding random seed.

The date range is hardcoded and might need to be adjusted for different exercises. Also, the random number generation isn't seeded, which means you'll get the same sequence of dates each time the program runs.

+// DateRange defines the bounds for random date generation
+type DateRange struct {
+    Start, End time.Time
+}
+
+func init() {
+    rand.Seed(time.Now().UnixNano())
+}
+
-func createRandomDates() []time.Time {
+func createRandomDates(dateRange DateRange) []time.Time {
 	listLength := rand.Intn(RandomCeiling-RandomFloor) + RandomFloor
 	list := make([]time.Time, listLength)
 
-	lowestDate := time.Date(2024, 10, 15, 0, 0, 0, 0, time.UTC)
-	highestDate := time.Date(2025, 1, 15, 0, 0, 0, 0, time.UTC)
-
 	for i := 0; i < listLength; i++ {
-		list[i] = randomDateWithin(lowestDate, highestDate)
+		list[i] = randomDateWithin(dateRange.Start, dateRange.End)
 	}
 	return list
 }

52-56: Normalize generated times to midnight.

The current implementation can generate dates with random times. For consistency in date comparison, consider normalizing all times to midnight.

 func randomDateWithin(low, high time.Time) time.Time {
 	randomTime := rand.Int63n(high.Unix()-low.Unix()) + low.Unix()
-	return time.Unix(randomTime, 0)
+	date := time.Unix(randomTime, 0)
+	return time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, time.UTC)
 }
src/main/java/de/tum/cit/aet/artemis/programming/service/TemplateUpgradePolicyService.java (1)

35-36: LGTM! Consider extracting language sets for better maintainability.

The changes correctly implement Go support by moving it to the supported languages case. The implementation follows the existing pattern of using defaultRepositoryUpgradeService for non-Java languages.

Consider extracting the language sets into static final Sets for better maintainability:

+    private static final Set<ProgrammingLanguage> DEFAULT_SUPPORTED_LANGUAGES = 
+        Set.of(ProgrammingLanguage.KOTLIN, ProgrammingLanguage.PYTHON, /* ... */, ProgrammingLanguage.GO);
+    private static final Set<ProgrammingLanguage> UNSUPPORTED_LANGUAGES = 
+        Set.of(ProgrammingLanguage.SQL, /* ... */, ProgrammingLanguage.PHP);

     public TemplateUpgradeService getUpgradeService(ProgrammingLanguage programmingLanguage) {
         return switch (programmingLanguage) {
             case JAVA -> javaRepositoryUpgradeService;
-            case KOTLIN, PYTHON, C, HASKELL, VHDL, ASSEMBLER, SWIFT, OCAML, EMPTY, RUST, JAVASCRIPT, R, C_PLUS_PLUS, TYPESCRIPT, C_SHARP, GO -> defaultRepositoryUpgradeService;
-            case SQL, MATLAB, BASH, RUBY, POWERSHELL, ADA, DART, PHP -> throw new UnsupportedOperationException("Unsupported programming language: " + programmingLanguage);
+            case _ when DEFAULT_SUPPORTED_LANGUAGES.contains(programmingLanguage) -> defaultRepositoryUpgradeService;
+            case _ when UNSUPPORTED_LANGUAGES.contains(programmingLanguage) -> 
+                throw new UnsupportedOperationException("Unsupported programming language: " + programmingLanguage);
+            default -> throw new IllegalArgumentException("Unknown programming language: " + programmingLanguage);
         };
     }

This refactoring would:

  1. Make it easier to maintain the language lists
  2. Improve readability
  3. Add better error handling for unknown languages
  4. Make the code more resilient to future language additions
src/main/resources/templates/go/solution/client/client.go (3)

18-41: Add error handling and improve logging

The main function could benefit from better error handling and more detailed logging:

  1. The Sort() method might return an error that should be handled
  2. Adding iteration numbers in the output would make the demo more clear

Consider this improvement:

 for i := 0; i < Iterations; i++ {
+    fmt.Printf("\nIteration %d:\n", i+1)
     dates := createRandomDates()

     context.SetDates(dates)
     policy.Configure()

     fmt.Println("Unsorted Array of course dates:")
     printDates(dates)
-    fmt.Println()
 
-    context.Sort()
+    if err := context.Sort(); err != nil {
+        fmt.Printf("Error sorting dates: %v\n", err)
+        continue
+    }

     fmt.Println("Sorted Array of course dates:")
     printDates(dates)
-    fmt.Println()
 }

43-55: Extract date range as constants

The date range for random date generation is hard-coded. Consider extracting these values as constants for better maintainability.

 const (
     Iterations    = 10
     RandomFloor   = 5
     RandomCeiling = 15
+    StartDate     = "2024-10-15"
+    EndDate       = "2025-01-15"
 )

 func createRandomDates() []time.Time {
     listLength := rand.Intn(RandomCeiling-RandomFloor) + RandomFloor
     list := make([]time.Time, listLength)

-    lowestDate := time.Date(2024, 10, 15, 0, 0, 0, 0, time.UTC)
-    highestDate := time.Date(2025, 1, 15, 0, 0, 0, 0, time.UTC)
+    lowestDate, _ := time.Parse("2006-01-02", StartDate)
+    highestDate, _ := time.Parse("2006-01-02", EndDate)

63-68: Consider making date format configurable

The printDates function uses a fixed date format. Consider making it more flexible by accepting a format string parameter.

-func printDates(dates []time.Time) {
+func printDates(dates []time.Time, format string) {
+    if format == "" {
+        format = time.DateOnly
+    }
     for _, date := range dates {
-        fmt.Println(date.Format(time.DateOnly))
+        fmt.Println(date.Format(format))
     }
 }
src/main/java/de/tum/cit/aet/artemis/programming/domain/ProgrammingLanguage.java (1)

Line range hint 1-100: Consider adding package name validation for Go.

Since Go has strict package naming conventions (lowercase letters, no underscores), consider adding package name validation similar to other languages.

Would you like me to propose an implementation for Go package name validation?

src/main/resources/templates/go/test/behavior/behavior_test.go (3)

71-83: Improve test implementation

Several improvements could make the tests more maintainable and robust:

  1. The threshold value of 10 should be defined as a constant
  2. Excessive use of interface{} and type assertions could be avoided
  3. Test cases could be table-driven for better maintainability

Consider this refactoring:

const sizeThreshold = 10

type testCase struct {
    name     string
    size     int
    expected string // "merge" or "bubble"
}

func TestSortStrategySelection(t *testing.T) {
    cases := []testCase{
        {"small list", 3, "bubble"},
        {"large list", 11, "merge"},
    }
    
    for _, tc := range cases {
        t.Run(tc.name, func(t *testing.T) {
            defer handlePanic(t)
            
            dates := make([]time.Time, tc.size)
            strategy := configurePolicyAndContext(dates)
            
            switch tc.expected {
            case "merge":
                if _, ok := strategy.(*${packageName}.MergeSort); !ok {
                    t.Errorf("expected MergeSort for size %d", tc.size)
                }
            case "bubble":
                if _, ok := strategy.(*${packageName}.BubbleSort); !ok {
                    t.Errorf("expected BubbleSort for size %d", tc.size)
                }
            }
        })
    }
}

Also applies to: 85-97


99-111: Simplify configuration helper function

The configurePolicyAndContext function uses multiple type assertions which could be simplified.

Consider this simpler approach:

func configurePolicyAndContext(dates []time.Time) SortStrategy {
    context := ${packageName}.NewContext()
    policy := ${packageName}.NewPolicy(context)
    
    context.SetDates(dates)
    policy.Configure()
    
    return context.GetSortAlgorithm()
}

54-69: Enhance test data coverage

The test dates could include more edge cases:

  • Dates with same day but different times
  • Dates in same month
  • Dates across different time zones

Consider adding these test cases:

dates := []time.Time{
    time.Date(2018, 11, 8, 10, 0, 0, 0, time.UTC),
    time.Date(2018, 11, 8, 9, 0, 0, 0, time.UTC),
    time.Date(2018, 11, 15, 0, 0, 0, 0, time.UTC),
    time.Date(2018, 11, 1, 0, 0, 0, 0, time.UTC),
    time.Date(2017, 4, 15, 0, 0, 0, 0, time.UTC),
    time.Date(2016, 2, 15, 0, 0, 0, 0, time.Local),
}
src/main/resources/templates/go/readme (1)

89-91: Consider adding performance guidance for QuickSort implementation.

The optional challenges could benefit from additional guidance about QuickSort's performance characteristics to help students make informed decisions about when to use it in the Policy class.

Consider adding:

  • Average, best, and worst-case time complexities
  • Space complexity
  • Typical use cases where QuickSort excels
  • Scenarios where QuickSort might be preferred over MergeSort
src/main/java/de/tum/cit/aet/artemis/programming/service/jenkins/JenkinsProgrammingLanguageFeatureService.java (1)

44-44: Add documentation for feature flags

Consider adding documentation to explain the boolean parameters in ProgrammingLanguageFeature. This would improve maintainability and make it clearer what each feature flag represents.

Example improvement:

 programmingLanguageFeatures.put(GO, new ProgrammingLanguageFeature(
+    // Language identifier
     GO,
+    // Static code analysis support
     false,
+    // Coverage reporting support
     false,
+    // Third feature: <description>
     true,
+    // Fourth feature: <description>
     true,
+    // Fifth feature: <description>
     false,
+    // Supported project types
     List.of(),
+    // Eighth feature: <description>
     false,
+    // Ninth feature: <description>
     false));
src/main/webapp/app/shared/constants/input.constants.ts (1)

50-51: Add a note about package naming conventions.

While the documentation accurately describes the technical requirements, consider adding a note about Go's package naming conventions (e.g., using short, lowercase, single-word names) to help developers follow best practices.

Add this line to the documentation:

 // Go package name Regex derived from (https://go.dev/ref/spec#Package_clause) limited to ASCII. Package names are identifiers.
+// Note: By convention, packages should use short, lowercase, single-word names without underscores.
 // They allow letters, digits and underscore. They cannot start with a digit. The package name cannot be a keyword or "_".
src/main/java/de/tum/cit/aet/artemis/plagiarism/service/ProgrammingPlagiarismDetectionService.java (1)

Line range hint 321-330: Consider refactoring the language mapping logic

The switch statement is growing large with many language cases. Consider refactoring this into a more maintainable structure, such as:

  1. A map-based lookup
  2. A factory pattern
  3. A strategy registry

This would make it easier to add new languages and maintain the code.

Example refactoring using a map-based approach:

-    private Language getJPlagProgrammingLanguage(ProgrammingExercise programmingExercise) {
-        return switch (programmingExercise.getProgrammingLanguage()) {
-            case C -> new CLanguage();
-            case C_PLUS_PLUS -> new CPPLanguage();
-            // ... other cases
-            case EMPTY, PHP, DART -> throw new BadRequestAlertException(
-                    "Programming language " + programmingExercise.getProgrammingLanguage() + " not supported for plagiarism check.",
-                    "ProgrammingExercise",
-                    "notSupported");
-        };
-    }
+    private static final Map<ProgrammingLanguage, Supplier<Language>> LANGUAGE_FACTORIES = Map.ofEntries(
+        Map.entry(ProgrammingLanguage.C, CLanguage::new),
+        Map.entry(ProgrammingLanguage.C_PLUS_PLUS, CPPLanguage::new),
+        Map.entry(ProgrammingLanguage.GO, GoLanguage::new)
+        // ... other entries
+    );
+
+    private Language getJPlagProgrammingLanguage(ProgrammingExercise programmingExercise) {
+        var languageFactory = LANGUAGE_FACTORIES.get(programmingExercise.getProgrammingLanguage());
+        if (languageFactory == null) {
+            throw new BadRequestAlertException(
+                "Programming language " + programmingExercise.getProgrammingLanguage() + " not supported for plagiarism check.",
+                "ProgrammingExercise",
+                "notSupported"
+            );
+        }
+        return languageFactory.get();
+    }
src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseFactory.java (1)

143-148: Consolidate package naming logic to avoid duplication

The package naming logic is currently split between two locations:

  1. The general language check in populateUnreleasedProgrammingExercise(ProgrammingExercise, ProgrammingLanguage)
  2. The Swift-specific check in populateUnreleasedProgrammingExercise(ProgrammingExercise, String, String, boolean, boolean, ProgrammingLanguage)

This could lead to maintenance issues and inconsistencies.

Consider:

  1. Creating a dedicated method for determining package names based on programming language
  2. Centralizing all language-specific package naming logic in one place
  3. Reusing this method across all variants of populateUnreleasedProgrammingExercise

Example:

private static String getDefaultPackageName(ProgrammingLanguage language) {
    return switch (language) {
        case JAVA, KOTLIN -> "de.test";
        case SWIFT -> "swiftTest";
        case GO -> "test";
        default -> "testPackage";
    };
}

Also applies to: 516-521

src/main/java/de/tum/cit/aet/artemis/programming/service/jenkins/build_plan/JenkinsBuildPlanService.java (1)

187-188: Consider refactoring language handling for better maintainability.

The current switch expression groups multiple languages together, which could make it harder to add language-specific configurations in the future. Consider restructuring to allow for language-specific builders when needed.

-case JAVA, KOTLIN, PYTHON, C, HASKELL, SWIFT, EMPTY, RUST, JAVASCRIPT, R, C_PLUS_PLUS, TYPESCRIPT, C_SHARP, GO -> jenkinsBuildPlanCreator;
+private static final Set<ProgrammingLanguage> SUPPORTED_LANGUAGES = Set.of(
+    ProgrammingLanguage.JAVA, ProgrammingLanguage.KOTLIN, ProgrammingLanguage.PYTHON,
+    ProgrammingLanguage.C, ProgrammingLanguage.HASKELL, ProgrammingLanguage.SWIFT,
+    ProgrammingLanguage.EMPTY, ProgrammingLanguage.RUST, ProgrammingLanguage.JAVASCRIPT,
+    ProgrammingLanguage.R, ProgrammingLanguage.C_PLUS_PLUS, ProgrammingLanguage.TYPESCRIPT,
+    ProgrammingLanguage.C_SHARP, ProgrammingLanguage.GO
+);
+
+case var lang when SUPPORTED_LANGUAGES.contains(lang) -> jenkinsBuildPlanCreator;
src/test/javascript/spec/component/programming-exercise/programming-exercise-update.component.spec.ts (1)

538-538: LGTM with suggestions for improved test coverage.

The package name pattern constants are correctly used in the test assertions. However, consider adding the following test cases for more comprehensive coverage:

  1. Test invalid package names against these patterns
  2. Test edge cases (empty strings, special characters)
  3. Test the pattern validation behavior when switching between languages

Example test cases to add:

it('should validate package names against language-specific patterns', () => {
    // Swift invalid cases
    comp.programmingExercise.programmingLanguage = ProgrammingLanguage.SWIFT;
    comp.programmingExercise.packageName = 'invalid.package';
    expect(comp.getInvalidReasons()).toContainEqual({
        translateKey: 'artemisApp.exercise.form.packageName.pattern.SWIFT',
        translateValues: {},
    });

    // Java/Kotlin invalid cases
    comp.programmingExercise.programmingLanguage = ProgrammingLanguage.JAVA;
    comp.programmingExercise.packageName = 'Invalid.Package';
    expect(comp.getInvalidReasons()).toContainEqual({
        translateKey: 'artemisApp.exercise.form.packageName.pattern.JAVA',
        translateValues: {},
    });
});

it('should revalidate package name when switching languages', () => {
    // Valid Java package name
    comp.programmingExercise.programmingLanguage = ProgrammingLanguage.JAVA;
    comp.programmingExercise.packageName = 'com.example';
    expect(comp.getInvalidReasons()).not.toContainEqual({
        translateKey: 'artemisApp.exercise.form.packageName.pattern.JAVA',
        translateValues: {},
    });

    // Same package name should be invalid for Swift
    comp.onProgrammingLanguageChange(ProgrammingLanguage.SWIFT);
    expect(comp.getInvalidReasons()).toContainEqual({
        translateKey: 'artemisApp.exercise.form.packageName.pattern.SWIFT',
        translateValues: {},
    });
});

Also applies to: 564-564

src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseTestService.java (1)

530-531: Consider refactoring language-specific package name logic

The current implementation hardcodes special cases for Java and Kotlin. Consider extracting this logic into a dedicated helper method or language-specific configuration for better maintainability.

-if (programmingLanguageFeature.packageNameRequired() && language != JAVA && language != KOTLIN) {
-    exercise.setPackageName("testPackage");
+// Extract to helper method
+if (shouldSetDefaultPackageName(programmingLanguageFeature, language)) {
+    exercise.setPackageName(DEFAULT_PACKAGE_NAME);
}

+// Add helper method
+private boolean shouldSetDefaultPackageName(ProgrammingLanguageFeature feature, ProgrammingLanguage language) {
+    return feature.packageNameRequired() && !LANGUAGES_WITH_CUSTOM_PACKAGES.contains(language);
+}

+// Add constant
+private static final Set<ProgrammingLanguage> LANGUAGES_WITH_CUSTOM_PACKAGES = 
+    Set.of(ProgrammingLanguage.JAVA, ProgrammingLanguage.KOTLIN);
+private static final String DEFAULT_PACKAGE_NAME = "testPackage";
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b5857b7 and 2b3b4c7.

⛔ Files ignored due to path filters (6)
  • src/main/resources/config/application.yml is excluded by !**/*.yml
  • src/main/resources/templates/aeolus/go/default.yaml is excluded by !**/*.yaml
  • src/main/resources/templates/go/exercise/go.mod is excluded by !**/*.mod
  • src/main/resources/templates/go/solution/go.mod is excluded by !**/*.mod
  • src/main/resources/templates/go/test/go.mod is excluded by !**/*.mod
  • src/test/resources/config/application.yml is excluded by !**/*.yml
📒 Files selected for processing (40)
  • build.gradle (1 hunks)
  • docs/user/exercises/programming-exercise-features.inc (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/plagiarism/service/ProgrammingPlagiarismDetectionService.java (3 hunks)
  • src/main/java/de/tum/cit/aet/artemis/programming/domain/ProgrammingLanguage.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseRepositoryService.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseService.java (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/programming/service/TemplateUpgradePolicyService.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/programming/service/ci/ContinuousIntegrationService.java (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/programming/service/jenkins/JenkinsProgrammingLanguageFeatureService.java (2 hunks)
  • src/main/java/de/tum/cit/aet/artemis/programming/service/jenkins/build_plan/JenkinsBuildPlanService.java (1 hunks)
  • src/main/java/de/tum/cit/aet/artemis/programming/service/localci/LocalCIProgrammingLanguageFeatureService.java (2 hunks)
  • src/main/resources/templates/aeolus/go/default.sh (1 hunks)
  • src/main/resources/templates/go/exercise/bubblesort.go (1 hunks)
  • src/main/resources/templates/go/exercise/client/client.go (1 hunks)
  • src/main/resources/templates/go/exercise/context.go (1 hunks)
  • src/main/resources/templates/go/exercise/mergesort.go (1 hunks)
  • src/main/resources/templates/go/exercise/policy.go (1 hunks)
  • src/main/resources/templates/go/exercise/sortstrategy.go (1 hunks)
  • src/main/resources/templates/go/readme (1 hunks)
  • src/main/resources/templates/go/solution/bubblesort.go (1 hunks)
  • src/main/resources/templates/go/solution/client/client.go (1 hunks)
  • src/main/resources/templates/go/solution/context.go (1 hunks)
  • src/main/resources/templates/go/solution/mergesort.go (1 hunks)
  • src/main/resources/templates/go/solution/policy.go (1 hunks)
  • src/main/resources/templates/go/solution/sortstrategy.go (1 hunks)
  • src/main/resources/templates/go/test/behavior/behavior_test.go (1 hunks)
  • src/main/resources/templates/go/test/structural/structural_test.go (1 hunks)
  • src/main/resources/templates/jenkins/go/regularRuns/pipeline.groovy (1 hunks)
  • src/main/webapp/app/entities/programming/programming-exercise.model.ts (1 hunks)
  • src/main/webapp/app/exercises/programming/manage/update/programming-exercise-creation-config.ts (0 hunks)
  • src/main/webapp/app/exercises/programming/manage/update/programming-exercise-update.component.ts (4 hunks)
  • src/main/webapp/app/exercises/programming/manage/update/update-components/language/programming-exercise-language.component.html (1 hunks)
  • src/main/webapp/app/exercises/programming/manage/update/update-components/language/programming-exercise-language.component.ts (2 hunks)
  • src/main/webapp/app/shared/constants/input.constants.ts (1 hunks)
  • src/main/webapp/i18n/de/exercise.json (1 hunks)
  • src/main/webapp/i18n/en/exercise.json (1 hunks)
  • src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseFactory.java (1 hunks)
  • src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseTestService.java (3 hunks)
  • src/test/javascript/spec/component/programming-exercise/programming-exercise-update.component.spec.ts (3 hunks)
  • src/test/javascript/spec/component/programming-exercise/update-components/programming-exercise-creation-config-mock.ts (0 hunks)
💤 Files with no reviewable changes (2)
  • src/main/webapp/app/exercises/programming/manage/update/programming-exercise-creation-config.ts
  • src/test/javascript/spec/component/programming-exercise/update-components/programming-exercise-creation-config-mock.ts
✅ Files skipped from review due to trivial changes (1)
  • src/main/resources/templates/go/exercise/sortstrategy.go
🧰 Additional context used
📓 Path-based instructions (18)
src/main/java/de/tum/cit/aet/artemis/plagiarism/service/ProgrammingPlagiarismDetectionService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/programming/domain/ProgrammingLanguage.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseRepositoryService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/programming/service/TemplateUpgradePolicyService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/programming/service/ci/ContinuousIntegrationService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/programming/service/jenkins/JenkinsProgrammingLanguageFeatureService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/programming/service/jenkins/build_plan/JenkinsBuildPlanService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/java/de/tum/cit/aet/artemis/programming/service/localci/LocalCIProgrammingLanguageFeatureService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

src/main/webapp/app/entities/programming/programming-exercise.model.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

src/main/webapp/app/exercises/programming/manage/update/programming-exercise-update.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

src/main/webapp/app/exercises/programming/manage/update/update-components/language/programming-exercise-language.component.html (1)

Pattern src/main/webapp/**/*.html: @if and @for are new and valid Angular syntax replacing *ngIf and *ngFor. They should always be used over the old style.

src/main/webapp/app/exercises/programming/manage/update/update-components/language/programming-exercise-language.component.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

src/main/webapp/app/shared/constants/input.constants.ts (1)

Pattern src/main/webapp/**/*.ts: angular_style:https://angular.io/guide/styleguide;methods_in_html:false;lazy_loading:true;code_reuse:true;tests:meaningful;types:PascalCase;enums:PascalCase;funcs:camelCase;props:camelCase;no_priv_prefix:true;strings:single_quotes;localize:true;btns:functionality;links:navigation;icons_text:newline;labels:associate;code_style:arrow_funcs,curly_braces,open_braces_same_line,indent_4;memory_leak_prevention:true;routes:naming_schema;chart_framework:ngx-charts;responsive_layout:true

src/main/webapp/i18n/de/exercise.json (1)

Pattern src/main/webapp/i18n/de/**/*.json: German language translations should be informal (dutzen) and should never be formal (sietzen). So the user should always be addressed with "du/dein" and never with "sie/ihr".

src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseFactory.java (1)

Pattern src/test/java/**/*.java: test_naming: descriptive; test_size: small_specific; fixed_data: true; junit5_features: true; assert_use: assertThat; assert_specificity: true; archunit_use: enforce_package_rules; db_query_count_tests: track_performance; util_service_factory_pattern: true; avoid_db_access: true; mock_strategy: static_mocks; context_restart_minimize: true

src/test/java/de/tum/cit/aet/artemis/programming/util/ProgrammingExerciseTestService.java (1)

Pattern src/test/java/**/*.java: test_naming: descriptive; test_size: small_specific; fixed_data: true; junit5_features: true; assert_use: assertThat; assert_specificity: true; archunit_use: enforce_package_rules; db_query_count_tests: track_performance; util_service_factory_pattern: true; avoid_db_access: true; mock_strategy: static_mocks; context_restart_minimize: true

src/test/javascript/spec/component/programming-exercise/programming-exercise-update.component.spec.ts (1)

Pattern src/test/javascript/spec/**/*.ts: jest: true; mock: NgMocks; bad_practices: avoid_full_module_import; perf_improvements: mock_irrelevant_deps; service_testing: mock_http_for_logic; no_schema: avoid_NO_ERRORS_SCHEMA; expectation_specificity: true; solutions: {boolean: toBeTrue/False, reference: toBe, existence: toBeNull/NotNull, undefined: toBeUndefined, class_obj: toContainEntries/toEqual, spy_calls: {not_called: not.toHaveBeenCalled, once: toHaveBeenCalledOnce, with_value: toHaveBeenCalledWith|toHaveBeenCalledExactlyOnceWith}}

📓 Learnings (2)
src/main/java/de/tum/cit/aet/artemis/programming/service/TemplateUpgradePolicyService.java (1)
Learnt from: magaupp
PR: ls1intum/Artemis#9074
File: src/main/java/de/tum/in/www1/artemis/service/programming/TemplateUpgradePolicyService.java:35-35
Timestamp: 2024-11-12T12:51:46.554Z
Learning: The `defaultRepositoryUpgradeService` in the `TemplateUpgradePolicyService` is used as a default for all non-JAVA languages, with specialized services added based on testing outcomes if necessary.
src/main/resources/templates/aeolus/go/default.sh (1)
Learnt from: magaupp
PR: ls1intum/Artemis#8802
File: src/main/resources/templates/aeolus/rust/default.sh:14-24
Timestamp: 2024-11-12T12:51:46.554Z
Learning: The `default.sh` script in the `src/main/resources/templates/aeolus/rust/` directory is auto-generated by Aeolus and should not be manually edited. Changes need to be made in the Aeolus generator settings or templates.
🪛 Shellcheck (0.10.0)
src/main/resources/templates/aeolus/go/default.sh

[warning] 6-6: testWorkingDirectory is referenced but not assigned.

(SC2154)

🔇 Additional comments (52)
src/main/resources/templates/go/solution/sortstrategy.go (3)

3-4: LGTM! Import statement is clean and necessary

The import of the time package is required for the time.Time type used in the interface.


1-7: Verify integration with test templates

Since this is part of a new Go template implementation, we should verify the test setup.

✅ Verification successful

Test integration is properly implemented

The verification shows comprehensive test coverage and proper integration:

  • Both structural and behavioral tests are present (structural_test.go and behavior_test.go)
  • Tests verify the SortStrategy interface implementation for both sorting algorithms
  • Behavioral tests confirm correct sorting functionality
  • Tests validate the strategy selection logic based on input size
  • Complete template structure exists with exercise and solution implementations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test setup and integration

# Check for test files in the Go template directory
echo "Checking for test files:"
fd -e go test src/main/resources/templates/go/

# Check for testing framework setup
echo "Checking for go-junit-report integration:"
rg -l "go-junit-report" src/main/resources/templates/go/

Length of output: 387


Script:

#!/bin/bash
# Let's examine the test files to verify integration with SortStrategy
echo "Checking test content for SortStrategy usage:"
rg -A 5 "SortStrategy" src/main/resources/templates/go/test/

# Check for any sorting-related test implementations
echo "Checking for sorting-related test patterns:"
rg -A 5 "Sort|PerformSort" src/main/resources/templates/go/test/

# Let's also check if there are any other related template files
echo "Checking for related template files:"
fd . src/main/resources/templates/go/ -e go --exclude '*test.go'

Length of output: 17278


1-1: LGTM! Verify package name replacement mechanism

The package declaration with placeholder follows the correct template syntax.

Let's verify the package name replacement mechanism:

✅ Verification successful

Package name placeholder usage is consistent and properly handled

The verification shows that:

  • The ${packageName} placeholder is consistently used across all Go template files (exercise, solution, and test directories)
  • The placeholder is used correctly in both package declarations and import paths
  • The replacement mechanism is implemented in ProgrammingExerciseRepositoryService.java, which sanitizes the package name and handles the replacement
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the package name placeholder is consistently used across Go templates
# and verify the replacement mechanism in the codebase

# Search for package name placeholder usage in Go files
echo "Checking package name placeholder usage in Go templates:"
rg -g "*.go" "\${packageName}" src/main/resources/templates/go/

# Search for the code that handles package name replacement
echo "Checking package name replacement implementation:"
rg -l "packageName.*replace|replacePackageName" src/main/

Length of output: 660


Script:

#!/bin/bash
# Let's try a different approach to search for package name placeholder
echo "Checking package name placeholder in Go templates:"
rg -F '${packageName}' src/main/resources/templates/go/

# Let's examine the implementation files found
echo -e "\nChecking package name replacement in ProgrammingExerciseRepositoryService:"
rg -A 5 "packageName.*replace|replacePackageName" src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseRepositoryService.java

echo -e "\nChecking package name replacement in StructuralTestCaseService:"
rg -A 5 "packageName.*replace|replacePackageName" src/main/java/de/tum/cit/aet/artemis/programming/service/hestia/structural/StructuralTestCaseService.java

Length of output: 4904

src/main/resources/templates/go/exercise/context.go (1)

1-1: Verify template variable replacement mechanism

The package name uses the template variable ${packageName}. Let's ensure this follows the project's templating conventions and is properly handled during exercise generation.

✅ Verification successful

Template variable ${packageName} follows consistent usage pattern

The verification shows that the ${packageName} template variable is consistently used across all Go files in the exercise template directory:

  • Used in package declaration in all .go files: bubblesort.go, context.go, mergesort.go, policy.go, sortstrategy.go
  • Used in module declaration in go.mod
  • Follows the same pattern across all files

This consistent usage indicates proper template variable handling and follows the project's templating conventions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of the packageName template variable
# and verify the template variable replacement mechanism across Go templates

# Check for consistent usage of ${packageName} in Go templates
rg -l '\$\{packageName\}' 'src/main/resources/templates/go/**/*.go'

# Check if there's a test that verifies package name replacement
rg -l "packageName.*[Tt]est" 'src/test/**/*.java'

Length of output: 260


Script:

#!/bin/bash
# Let's try without the glob patterns that might be causing issues
# First, let's find all Go template files
fd -e go . src/main/resources/templates

# Then search for packageName usage in Go files
rg -l '\$\{packageName\}'

# Find test files that might verify template processing
fd -e java . src/test

Length of output: 62165


Script:

#!/bin/bash
# Let's check for template variable usage in Go files and related test files
# First, find all Go template files in the exercise directory
fd -e go . src/main/resources/templates/go/exercise

# Then check for packageName variable usage in Go files
rg -p '\$\{packageName\}' src/main/resources/templates/go/exercise/

# Check for any test files that verify template processing
rg -p 'packageName.*[Tt]est' src/test/java/de/tum/cit/aet/artemis/programming/

Length of output: 1010

src/main/resources/templates/go/exercise/mergesort.go (1)

1-7: Verify Go module setup

Ensure that the template includes proper Go module configuration for student exercises.

✅ Verification successful

Let me check the content of these go.mod files to ensure they are properly configured.


Go module configuration is properly set up

The template includes all necessary Go module configuration files:

  • Exercise and solution modules are correctly defined with templated package names
  • Test module is properly configured with module replacement for student workspace
  • Go version is consistently specified across all modules
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if go.mod exists in the template directory
fd -t f "go.mod" "src/main/resources/templates/go"

# Check if there are any Go-specific configuration files
fd -t f "go\." "src/main/resources/templates/go"

Length of output: 377


Script:

#!/bin/bash
# Check the content of go.mod files
echo "=== Exercise go.mod ==="
cat src/main/resources/templates/go/exercise/go.mod

echo -e "\n=== Solution go.mod ==="
cat src/main/resources/templates/go/solution/go.mod

echo -e "\n=== Test go.mod ==="
cat src/main/resources/templates/go/test/go.mod

Length of output: 587

src/main/resources/templates/go/exercise/bubblesort.go (2)

1-1: LGTM: Package declaration uses correct template syntax

The package declaration correctly uses the ${packageName} placeholder which will be replaced during exercise generation.


1-7: Verify test template existence

Since this is an exercise template that should work with Go's testing package and go-junit-report, we should verify the existence of corresponding test templates.

✅ Verification successful

Test templates are properly configured

The test setup is complete and well-structured with:

  • Behavioral tests in test/behavior/behavior_test.go that verify sorting functionality and algorithm selection
  • Structural tests in test/structural/structural_test.go that verify interface implementations
  • Both test files use Go's testing package and include proper panic handling
  • Tests are designed to work with the template's package name variable ${packageName}
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for corresponding test template files
fd "bubblesort_test.go" "src/main/resources/templates/go"

# Check for test helper or setup files
fd "test_helper|setup_test" "src/main/resources/templates/go"

Length of output: 117


Script:

#!/bin/bash
# Let's check the directory structure and content first
fd . "src/main/resources/templates/go" -t f

# Also check for any test-related files in the Go templates
rg -l "testing" "src/main/resources/templates/go"

Length of output: 1184


Script:

#!/bin/bash
# Let's check the content of the test files to understand the testing setup
cat src/main/resources/templates/go/test/behavior/behavior_test.go
cat src/main/resources/templates/go/test/structural/structural_test.go

Length of output: 4315

src/main/resources/templates/go/exercise/policy.go (1)

1-1: LGTM: Package declaration follows Go conventions

The template uses ${packageName} placeholder which will be replaced with the actual package name during exercise creation.

src/main/resources/templates/aeolus/go/default.sh (2)

1-2: LGTM: Proper shell configuration

The shebang and error handling setup are correct.


1-15: Verify if this file should be manually edited

Based on previous learnings from PR #8802, similar default.sh scripts in other language templates are auto-generated by Aeolus. Please verify if this file should be manually edited or if changes should be made in Aeolus generator settings.

🧰 Tools
🪛 Shellcheck (0.10.0)

[warning] 6-6: testWorkingDirectory is referenced but not assigned.

(SC2154)

src/main/resources/templates/go/solution/bubblesort.go (2)

1-4: LGTM! Clean package declaration and imports.

The package declaration using template variable and single required import follow Go best practices.


1-19: Verify consistency with other language templates.

As this is part of a new Go template implementation using the Strategy Pattern, we should verify it follows the same structure as other language templates.

✅ Verification successful

The previous results showed Java implementations but we need more context about Python templates and the strategy pattern implementation. This new script should help us find Python sorting implementations and the strategy pattern structure across the codebase.


Based on the search results, I can now verify the consistency of the Go template with other language templates. The implementation follows the same Strategy Pattern structure as seen in Java, Python, Swift, C#, and Kotlin templates, with similar method signatures and sorting logic. Let me highlight the key points:

Implementation is consistent with other language templates

  • All language templates implement a Strategy Pattern with a SortStrategy interface/protocol
  • The performSort method signature is consistent across languages, taking a collection of dates as input
  • The bubble sort implementation follows the same algorithm structure as other languages
  • The template includes proper package and import declarations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if other language templates follow similar structure
echo "Checking Java template..."
fd -e java "bubblesort.java" -x cat {} \;

echo "Checking Python template..."
fd -e py "bubblesort.py" -x cat {} \;

# Look for other strategy pattern implementations
echo "Checking for other sorting strategy implementations..."
rg -l "PerformSort|sort.*strategy" --type java --type python

Length of output: 1309


Script:

#!/bin/bash
# Let's try a different approach to find Python templates and strategy implementations

# Search for Python sorting files
echo "Searching for Python sorting files..."
fd -e py "sort" -x cat {} \;

# Search for strategy pattern interface/base class
echo "Searching for strategy pattern interface..."
fd -t f "Strategy" -x cat {} \;

# Search for other sorting implementations
echo "Searching for other sorting classes..."
fd -t f "Sort" -x cat {} \;

Length of output: 114599

src/main/resources/templates/go/solution/policy.go (2)

1-1: Verify template variable processing

The package name uses a template variable ${packageName}. Let's ensure this variable is properly processed during exercise generation.

✅ Verification successful

The first search didn't find the exact pattern, so let's broaden the search to understand how Go templates are processed in the system. This will help us verify if the ${packageName} variable is properly handled during template processing.


Based on the search results, I can now generate the final response as we have sufficient evidence about the template processing system:

Template variable ${packageName} is properly handled

The package name template variable is part of a well-established template processing system where:

  • The package name is validated specifically for Go using PACKAGE_NAME_PATTERN_FOR_GO pattern
  • The system includes proper sanitization of package names to prevent injection
  • The template variable is consistently used across all Go template files in the solution
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the template variable ${packageName} is consistently used across Go templates
# and verify the template processing mechanism

# Search for ${packageName} usage in Go templates
echo "Checking template variable usage in Go files:"
fd -e go . src/main/resources/templates/go -x grep -l '\${packageName}' {} \;

# Search for template processing code
echo "Checking template processing implementation:"
rg -l "packageName.*Go|Go.*packageName" src/main/

Length of output: 1157


Script:

#!/bin/bash
# Let's verify the template processing implementation more thoroughly
# by checking the template engine configuration and processing logic

# Search for Go template-related configuration and processing
echo "Checking Go template processing implementation:"
rg -l "template.*go|go.*template" src/main/java -g '!*.go'

# Check for package name processing specifically
echo "Checking package name processing:"
rg -A 5 "packageName.*=|setPackageName" src/main/java

Length of output: 9755


1-20: Verify Strategy pattern implementation completeness

The Policy implementation looks good but let's verify the existence and proper implementation of related components.

✅ Verification successful

Let me gather more information about the specific implementations to verify the completeness of the Strategy pattern.


Strategy pattern implementation is complete and correct

The verification confirms that all required components are properly implemented:

  • SortStrategy interface with PerformSort method
  • Context struct managing the strategy and dates
  • Two concrete strategies: BubbleSort and MergeSort, both implementing the PerformSort method
  • Policy correctly switches between strategies based on data size

The implementation follows the Strategy pattern principles with clean separation of concerns and proper interface adherence.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the complete Strategy pattern implementation

# Check for required related files
echo "Checking for required strategy pattern components:"
fd -e go . src/main/resources/templates/go/solution -x grep -l 'type.*Sort\|interface.*Strategy\|type.*Context' {} \;

# Verify interface implementation
echo "Checking sort strategy interface implementation:"
ast-grep --pattern 'type $_ interface {
    Sort($_)
}'

Length of output: 740


Script:

#!/bin/bash
# Check the content of strategy interface and concrete implementations

echo "=== Checking SortStrategy interface ==="
rg -A 5 "type.*Strategy.*interface" src/main/resources/templates/go/solution/sortstrategy.go

echo -e "\n=== Checking Context implementation ==="
rg -A 10 "type Context struct" src/main/resources/templates/go/solution/context.go

echo -e "\n=== Checking BubbleSort implementation ==="
rg -A 10 "type BubbleSort struct" src/main/resources/templates/go/solution/bubblesort.go

echo -e "\n=== Checking MergeSort implementation ==="
rg -A 10 "type MergeSort struct" src/main/resources/templates/go/solution/mergesort.go

Length of output: 1516

src/main/resources/templates/go/solution/context.go (2)

1-4: LGTM! Clean package declaration and imports

The package declaration with template variable and single required import follow Go best practices.


5-8: Verify the SortStrategy interface definition

The struct definition looks good, following Go conventions. However, we should verify the SortStrategy interface definition.

✅ Verification successful

SortStrategy interface is properly defined with PerformSort method

The SortStrategy interface is well-defined in src/main/resources/templates/go/solution/sortstrategy.go with the expected PerformSort method that takes a slice of time.Time as input. This matches perfectly with its usage in the Context struct.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Look for SortStrategy interface definition
# Expected: Interface definition with PerformSort method

# Search for SortStrategy interface definition
ast-grep --pattern 'type SortStrategy interface {
  $$$
}'

# Backup search using ripgrep
rg -p "type\s+SortStrategy\s+interface"

Length of output: 1469

src/main/resources/templates/go/solution/mergesort.go (2)

1-57: Verify test coverage

The implementation looks solid, but we should ensure comprehensive test coverage, including edge cases like empty slices, single elements, and already sorted inputs.

✅ Verification successful

Test coverage appears adequate

The implementation is well-tested with:

  • Structural test verifying the SortStrategy interface implementation
  • Behavioral test checking actual sorting functionality with test dates
  • Integration test verifying MergeSort selection for large lists (>10 elements)
  • Test data includes multiple elements through createTestDates()
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for test file and coverage
fd -e go "mergesort.*test\.go$"

Length of output: 33


Script:

#!/bin/bash
# Let's try a broader search for test files related to sorting
fd -e go "sort.*test\.go$"

# Also search for any references to MergeSort in test files
rg -l "MergeSort" --type go | grep "_test"

Length of output: 199


Script:

#!/bin/bash
# Let's examine the content of these test files to verify MergeSort coverage
rg "MergeSort" -A 5 -B 5 src/main/resources/templates/go/test/structural/structural_test.go
rg "MergeSort" -A 5 -B 5 src/main/resources/templates/go/test/behavior/behavior_test.go

Length of output: 1859


1-1: Verify template variable interpolation

The ${packageName} template variable needs to be properly interpolated during template processing.

✅ Verification successful

Let me analyze the results and generate one more verification script to check the template processing mechanism.


Let me try one final verification to check the template processing mechanism by looking at the broader context.


Based on the search results and previous findings, I can now generate the final response:

Template variable interpolation is handled by the system

The ${packageName} template variable is part of a well-established template processing system in the codebase:

  • The package name is validated using language-specific patterns (PACKAGE_NAME_PATTERN_FOR_GO)
  • The system has proper UI components for package name input
  • The package name is processed during programming exercise creation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there's a mechanism to process the ${packageName} template variable
rg -A 5 "packageName.*=|func.*packageName" 

Length of output: 29848


Script:

#!/bin/bash
# Check for template processing mechanism in Go files
rg -g "*.go" -B 3 -A 3 "\$\{packageName\}" 

# Check for any Go-specific template processing code
ast-grep --pattern 'func $name($$$) {
  $$$
  packageName $$$
  $$$
}'

Length of output: 240


Script:

#!/bin/bash
# Look for template processing related code for Go exercises
rg -g "*.java" -g "*.ts" "template.*go|go.*template" -B 2 -A 2

# Check for any template engine or processing utilities
rg -g "*.java" -g "*.ts" "TemplateProcessor|processTemplate" -B 2 -A 2

Length of output: 14496

src/main/resources/templates/go/test/structural/structural_test.go (1)

7-7: Verify template variable processing in import path

The import path contains a template variable ${packageName} which must be properly processed before compilation. Ensure that the template processing system correctly handles Go package naming conventions.

✅ Verification successful

Template variable ${packageName} is used consistently across Go files

The ${packageName} variable is used consistently throughout the Go template files in the codebase:

  • Used in package declarations across all Go source files
  • Used in import paths consistently as "artemis/${packageName}"
  • Used correctly in type references and instantiations
  • Part of a complete template structure with exercise, solution, and test files
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the template variable is used consistently across Go files
# and verify the package name pattern matches Go conventions

# Search for ${packageName} usage in Go files
rg -g "*.go" "\\\${packageName}"

# Check if there are any Go package declarations that might conflict
ast-grep --pattern 'package $_'

Length of output: 104950


Script:

#!/bin/bash
# Let's search for template variable usage in Go files specifically
rg -t go '\$\{packageName\}'

# Also check for any Go files in the templates directory
fd -e go . src/main/resources/templates/

Length of output: 3794

src/main/resources/templates/jenkins/go/regularRuns/pipeline.groovy (2)

11-12: Verify Docker configuration placeholders

The Docker configuration uses placeholder values that will be replaced during runtime. Ensure these placeholders match the expected format in the template processor.

✅ Verification successful

Based on the search results and the learning from magaupp that mentions "placeholder variables such as #dockerImage and #dockerArgs in Jenkins pipeline scripts are intentionally left in the scripts, as they are replaced by Java code during execution", I can generate the final response:

Docker configuration placeholders are correctly formatted

The placeholder values #dockerImage and #dockerArgs follow the consistent format used across all Jenkins pipeline templates in the project and are intentionally left as placeholders to be replaced by Java code during execution.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the placeholder format is consistent across other language templates
rg -g 'pipeline.groovy' "'#docker(Image|Args)'" src/main/resources/templates/jenkins/

Length of output: 4181


1-55: Overall implementation looks good with suggested improvements

The pipeline implementation follows the expected structure and provides the necessary functionality for Go exercise testing. Consider implementing the suggested improvements for better robustness and security.

✅ Verification successful

Let me check the implementation details of other templates to ensure complete consistency.


Implementation is consistent with other language templates

The Go pipeline implementation follows the same structure and patterns as other language templates:

  • Common method signatures (testRunner, runTestSteps, postBuildTasks)
  • Similar test stage implementation with language-specific test commands
  • Consistent JUnit report generation and handling
  • Proper Docker container usage
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify consistency with other language templates
echo "Checking for consistency with other language templates..."
rg -g 'pipeline.groovy' "testRunner|runTestSteps|postBuildTasks" src/main/resources/templates/jenkins/

Length of output: 7856


Script:

#!/bin/bash
# Check the test stage implementation in other templates
echo "Checking test stage implementation in other templates..."
rg -g 'pipeline.groovy' -B 2 -A 4 "stage\('Test'\)" src/main/resources/templates/jenkins/

Length of output: 6891

src/main/resources/templates/go/exercise/client/client.go (2)

1-8: LGTM! Package and imports are well-structured.

The package declaration and imports follow Go best practices and include all necessary packages for the implementation.


58-63: LGTM! The printDates function is well-implemented.

The function correctly uses the DateOnly format for consistent date representation.

src/main/resources/templates/go/solution/client/client.go (1)

11-16: LGTM!

Constants are well-defined with clear names and appropriate values for demonstration purposes.

src/main/java/de/tum/cit/aet/artemis/programming/domain/ProgrammingLanguage.java (1)

Line range hint 18-18: LGTM! GO enum constant is properly defined.

The GO enum constant follows the established pattern and uses the correct file extension.

src/main/resources/templates/go/test/behavior/behavior_test.go (1)

1-9: ⚠️ Potential issue

Package naming needs revision

The package name "test" is not idiomatic in Go. Test files should use the same package name as the code they're testing with a "_test" suffix.

Apply this change:

-package test
+package ${packageName}_test

Also, verify that the template variable ${packageName} in the import path will be correctly substituted during template processing.

src/main/resources/templates/go/readme (2)

42-83: Well-structured UML diagram following Go conventions.

The class diagram effectively illustrates the Strategy Pattern implementation and follows Go conventions with New* constructor naming. The relationships between components are clearly defined, and test coverage annotations provide helpful visual feedback.


11-12: Verify test file references exist and are properly implemented.

The instructions reference test files for both structural and behavioral tests. Let's verify these files exist and contain the referenced test cases.

Also applies to: 14-15

✅ Verification successful

Let me check the actual test file paths and content to verify if they match the references in the README.


Test file references are correctly implemented and match the README

The test files exist at the correct locations and contain the appropriate test cases:

  • src/main/resources/templates/go/test/structural/structural_test.go contains TestBubbleSort for structural verification
  • src/main/resources/templates/go/test/behavior/behavior_test.go contains TestBubbleSort for behavioral verification

The test files properly validate both the structure and behavior of the BubbleSort implementation, including interface compliance and correct sorting of time.Time slices.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify test files and test cases exist

# Check for test files
echo "Checking for test files..."
fd -e go -p "structural.*test\.go|behavior.*test\.go" "test"

# Check for specific test cases
echo -e "\nChecking for test cases..."
rg -A 2 "func Test(BubbleSort|MergeSort)" --type go

Length of output: 1361


Script:

#!/bin/bash
# Check the actual paths of test files
echo "Checking actual test file paths..."
fd -e go . src/main/resources/templates/go/test

# Check content of structural test file
echo -e "\nChecking structural test content..."
cat src/main/resources/templates/go/test/structural/structural_test.go

# Check content of behavior test file
echo -e "\nChecking behavior test content..."
cat src/main/resources/templates/go/test/behavior/behavior_test.go

Length of output: 4744

src/main/java/de/tum/cit/aet/artemis/programming/service/jenkins/JenkinsProgrammingLanguageFeatureService.java (2)

7-7: LGTM: Import statement follows guidelines

The static import for GO is properly placed with other language imports and follows Java import conventions.


44-44: Verify Go language feature configuration

Please verify that the feature configuration aligns with Go's capabilities:

  • No project types are specified (empty List.of())
  • Only the third and fourth features are enabled
  • Static code analysis and coverage are disabled
✅ Verification successful

Let me gather more specific information about Go language configuration and features.


Let me search for the ProgrammingLanguageFeature class definition to understand the boolean parameters.


Let me search for the actual ProgrammingLanguageFeature class definition to understand the boolean parameters.


Let me try a broader search to find the ProgrammingLanguageFeature definition.


Based on the search results, I can now provide a complete verification of the Go language feature configuration. The ProgrammingLanguageFeature record shows that the boolean parameters represent:

  1. sequentialTestRuns (false)
  2. staticCodeAnalysis (false)
  3. plagiarismCheckSupported (true)
  4. packageNameRequired (true)
  5. checkoutSolutionRepositoryAllowed (false)
  6. projectTypes (empty List)
  7. testwiseCoverageAnalysisSupported (false)
  8. auxiliaryRepositoriesSupported (false)

This configuration is consistent with Go's capabilities and limitations:

  • Static code analysis and sequential test runs are not supported
  • Package name is required (as per Go's conventions)
  • Plagiarism detection is supported
  • No specific project types are needed (Go has a standard project structure)
  • Test coverage analysis and auxiliary repositories are not supported

The configuration is appropriate for Go programming exercises

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Go-related configurations and tests to verify feature support
rg -l "GO|Go|go" --type java src/test

Length of output: 7787


Script:

#!/bin/bash
# Search for Go-related configurations and implementations
rg -A 10 "GO|Go|go" --type java src/main/java/de/tum/cit/aet/artemis/programming/ | grep -v "goto"

# Search for ProgrammingLanguageFeature class to understand the boolean parameters
ast-grep --pattern 'class ProgrammingLanguageFeature {
  $$$
}'

Length of output: 131391


Script:

#!/bin/bash
# Search for ProgrammingLanguageFeature class definition and its constructor
rg -A 20 "class ProgrammingLanguageFeature" src/main/java/de/tum/cit/aet/artemis/programming/

Length of output: 3455


Script:

#!/bin/bash
# Search for ProgrammingLanguageFeature record/class definition
rg -A 15 "record ProgrammingLanguageFeature|class ProgrammingLanguageFeature \{" src/main/java/de/tum/cit/aet/artemis/programming/domain/

Length of output: 139


Script:

#!/bin/bash
# Search for ProgrammingLanguageFeature in all Java files
rg -t java -B 2 -A 15 "ProgrammingLanguageFeature" src/main/java/

# Also search for Go-related configurations to understand the feature flags
rg -t java "GO.*ProgrammingLanguageFeature" src/main/java/

Length of output: 75037

src/main/webapp/app/shared/constants/input.constants.ts (1)

50-53: LGTM! Verify the Go package name pattern.

The implementation correctly follows Go's package naming rules and maintains consistency with other language patterns.

Let's verify the pattern against valid and invalid package names:

✅ Verification successful

Go package name pattern is correctly implemented and verified

The regex pattern for Go package names has been thoroughly tested and correctly validates:

  • All valid package names: 'main', 'mypackage', 'api', 'v1', 'math_utils', '_test'
  • Correctly rejects all invalid cases:
    • Go keywords ('package', 'if', 'type')
    • Names starting with digits ('1package')
    • Names with invalid characters ('my-package', 'my.package')
    • Single underscore ('_')
    • Empty string
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Test the Go package name pattern against various cases

# Create a temporary JavaScript file to test the regex
cat << 'EOF' > /tmp/test_pattern.js
const pattern = /^(?!(?:break|default|func|interface|select|case|defer|go|map|struct|chan|else|goto|package|switch|const|fallthrough|if|range|type|continue|for|import|return|var|_)$)[A-Za-z_][A-Za-z0-9_]*$/;

// Valid cases
const validCases = [
    'main',
    'mypackage',
    'api',
    'v1',
    'math_utils',
    '_test' // Valid in Go but uncommon
];

// Invalid cases
const invalidCases = [
    'package', // keyword
    '1package', // starts with number
    'my-package', // invalid character
    'my.package', // invalid character
    '_', // single underscore
    'if', // keyword
    'type', // keyword
    '' // empty
];

console.log('Testing valid cases:');
validCases.forEach(name => {
    console.log(`${name}: ${pattern.test(name)}`);
});

console.log('\nTesting invalid cases:');
invalidCases.forEach(name => {
    console.log(`${name}: ${pattern.test(name)}`);
});
EOF

# Run the test
node /tmp/test_pattern.js

Length of output: 259

src/main/java/de/tum/cit/aet/artemis/programming/service/localci/LocalCIProgrammingLanguageFeatureService.java (2)

9-9: LGTM!

The static import for GO follows the established pattern and maintains alphabetical ordering with other language imports.


51-51: LGTM! Configuration aligns with Go's capabilities.

The ProgrammingLanguageFeature configuration for Go is well-structured and appropriately enables:

  • Static code analysis
  • Package name validation
  • Linting support

Let's verify the static code analysis capability is properly supported:

src/main/webapp/app/entities/programming/programming-exercise.model.ts (2)

21-21: LGTM! The GO enum value follows the established pattern.

The addition of the GO programming language follows the correct naming convention and maintains consistency with other enum values.


21-21: Verify exhaustive handling of ProgrammingLanguage enum.

While the GO enum addition is correct, we should ensure all switch statements and type guards handling ProgrammingLanguage are updated to include the new GO case.

src/main/webapp/app/exercises/programming/manage/update/update-components/language/programming-exercise-language.component.ts (3)

12-12: LGTM! Import statement follows Angular conventions.

The import statement is properly formatted and follows Angular style guidelines.


48-49: Verify the necessity of Swift-related changes in Go PR.

While the property is correctly implemented following Angular guidelines, its addition seems unexpected in a PR focused on Go language support. Could you clarify the rationale for including Swift-related changes?

Let's check for related Swift pattern usage:


Line range hint 89-99: Verify Go package name validation integration.

The isPackageNameValid() method handles package name validation for different languages, but there's no explicit handling for Go. Please ensure that Go-specific package name validation is properly integrated.

Let's check for Go-specific validation patterns:

src/main/java/de/tum/cit/aet/artemis/programming/service/ci/ContinuousIntegrationService.java (2)

233-234: Consider Go's testing conventions.

Go's standard testing convention places test files alongside source files with a _test.go suffix, rather than in a separate "tests" directory. This architectural decision might need reconsideration.

Consider:

  1. Following Go's convention of co-located test files
  2. If separate test directory is required, document the reasoning

222-223: LGTM! Verify Go's checkout path convention.

The addition of Go to the supported languages list with "assignment" checkout path is consistent with other modern languages. However, let's verify that this aligns with Go's project structure conventions.

✅ Verification successful

Let me gather more information about the Go project structure in the codebase.


✓ Go's checkout path convention is correctly configured

The verification confirms that the "assignment" checkout path for Go is appropriate based on the codebase structure:

  • Go files are organized in a standard project layout under src/main/resources/templates/go/
  • The structure follows Go conventions with separate directories for exercise, solution, and test code
  • Each module has its own go.mod file in the appropriate directory
  • Test files are properly organized in dedicated test directories
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify Go's project structure conventions in the codebase
# Look for Go-specific project structure patterns to confirm the "assignment" directory convention

# Search for Go module files in assignment directories
fd -e mod -x dirname {} \; | grep -i "assignment"

# Search for Go package declarations to verify directory structure
rg -g "*.go" "package\s+main" -A 5

Length of output: 890


Script:

#!/bin/bash
# Search for Go-related files and their directory structure
fd -e go -x dirname {} \; | sort -u

# Look for Go-specific test files to understand the project layout
fd -e go -g "*_test.go"

# Check for any Go-specific configuration or build files
fd -g "go.*"

# Search for any documentation about Go project structure
rg -g "*.md" -i "go|golang" -A 3 -B 3

Length of output: 15367

src/main/webapp/app/exercises/programming/manage/update/update-components/language/programming-exercise-language.component.html (2)

Line range hint 7-7: LGTM: Consistent usage of new Angular control flow syntax

The template correctly uses the new @if and @for syntax throughout, which aligns with the coding guidelines requiring these over the older *ngIf and *ngFor directives.

Also applies to: 19-19, 23-23, 33-33, 38-38, 72-72, 91-91, 134-134, 147-147, 157-157, 182-182, 199-199, 217-217, 235-235


125-125: LGTM: Pattern validation moved to constant

The change from programmingExerciseCreationConfig.appNamePatternForSwift to APP_NAME_PATTERN_FOR_SWIFT improves maintainability by using a constant instead of a configuration object property.

Let's verify the constant is properly defined:

✅ Verification successful

Constant is properly defined and imported

The constant APP_NAME_PATTERN_FOR_SWIFT is correctly defined in src/main/webapp/app/shared/constants/input.constants.ts and properly imported in the component. The pattern enforces valid Swift identifiers by excluding Swift keywords and following Swift naming conventions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify APP_NAME_PATTERN_FOR_SWIFT constant definition
# Expected: Find the constant definition in component or constants file

# Search for the constant definition
rg "APP_NAME_PATTERN_FOR_SWIFT\s*=" -A 2

Length of output: 1258

docs/user/exercises/programming-exercise-features.inc (1)

48-49: LGTM: Go language support entry is correctly formatted and positioned.

The addition of Go to the programming language support table is consistent with the PR objectives and correctly indicates support for both Local CI and Jenkins.

src/main/java/de/tum/cit/aet/artemis/plagiarism/service/ProgrammingPlagiarismDetectionService.java (2)

36-36: LGTM!

The import statement follows Java conventions and is properly organized with other JPlag language imports.


321-321: LGTM!

The GO case follows the established pattern and is properly placed alphabetically among other supported languages.

src/main/java/de/tum/cit/aet/artemis/programming/service/jenkins/build_plan/JenkinsBuildPlanService.java (2)

187-188: LGTM! Go language support added correctly.

The addition of GO to the supported languages list follows the existing pattern and is consistent with other language implementations.


187-188: Verify Go-specific build configurations.

Since Go has been added as a supported language, ensure that the jenkinsBuildPlanCreator can handle Go-specific build configurations correctly.

✅ Verification successful

Based on the search results, I can see that there are no explicit Go-specific build configurations in the codebase. The only Go-related information found is that Go is included in a switch statement for language types, but no actual build configuration logic was found.

Let me gather more information by searching for Go-related build files and configurations:


Based on the search results, I can now provide a conclusive response about the Go build configurations:

Go build configurations are properly implemented and verified.

The codebase has appropriate Go-specific build configurations in place:

  • Jenkins pipeline configuration exists in templates/jenkins/go/regularRuns/pipeline.groovy
  • Aeolus build configuration exists in templates/aeolus/go/default.yaml and default.sh
  • Standard Go build files (go.mod) are present in the templates
  • Test execution is properly configured using go test ./... -json with JUnit report generation

The build configurations follow Go best practices with:

  • Proper test execution and reporting
  • Module management via go.mod
  • CI/CD integration through Jenkins and Aeolus
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for Go-specific build configurations in the Jenkins build plan creator

# Search for Go-specific build configurations
ast-grep --pattern 'case GO:
  $$$
'

# Search for Go-related test configurations
rg -A 5 'GO.*test'

# Search for Go build command configurations
rg -A 5 'go\s+build|go\s+test'

Length of output: 131288


Script:

#!/bin/bash
# Search for Go-specific build files and configurations
fd -t f '\.go$|go\.mod|go\.sum'

# Search for Go-related build commands and configurations
rg -i 'go\s+build|go\s+test|go\s+run|go\s+install|go\.mod|go\.sum'

# Look for Go-specific Jenkins pipeline configurations
rg -i 'golang|go\s+build|go\s+test' --type yaml

Length of output: 2245

build.gradle (1)

256-256: LGTM! Addition of Go language support is properly configured.

The Go language support is correctly added through the JPlag dependency, maintaining consistency with other language implementations.

Let's verify the JPlag version compatibility:

✅ Verification successful

✓ Go language support is properly configured with compatible JPlag version

The Go language module is being added with JPlag version 5.1.0, which matches the latest available version in the Maven repository. This ensures compatibility and proper functionality of the Go language support.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the jplag_version property is defined and get its value
# Look for jplag_version in gradle.properties or similar files
fd -t f "gradle.properties|*.gradle" -x grep -l "jplag_version"

# Verify if the Go language module is available in the specified version
curl -s "https://repo1.maven.org/maven2/de/jplag/golang/maven-metadata.xml" | grep -o "<version>.*</version>" | tail -n 1

Length of output: 534


Script:

#!/bin/bash
# Let's fix the previous command and check for jplag_version in gradle files
fd -e gradle -e properties | xargs grep -l "jplag_version"

# Get the actual jplag_version being used
grep "jplag_version" gradle.properties || grep "jplag_version =" build.gradle

Length of output: 148

src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseRepositoryService.java (1)

659-659: LGTM! The Go package name handling is correctly implemented.

The implementation follows the same pattern as other languages and correctly sets the package name placeholder for Go files.

src/main/java/de/tum/cit/aet/artemis/programming/service/ProgrammingExerciseService.java (2)

107-127: LGTM! Well-documented regex patterns for package name validation.

The implementation correctly:

  • Follows the Go language specification for package names
  • Handles Go keywords and identifier rules
  • Uses static final fields for performance
  • Includes proper documentation with reference links

438-443: LGTM! Clean and maintainable pattern matching logic.

The switch expression:

  • Uses modern Java syntax
  • Handles all supported languages consistently
  • Has appropriate error handling for unsupported languages
src/test/javascript/spec/component/programming-exercise/programming-exercise-update.component.spec.ts (1)

79-79: LGTM!

The import statement for package name pattern constants is well-organized and follows the project's import conventions.

Copy link

@HawKhiem HawKhiem left a comment

Choose a reason for hiding this comment

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

Tested on TS3. I got build fail for both the solution and the template

image

@magaupp
Copy link
Contributor Author

magaupp commented Nov 26, 2024

Thank you for the test. It seems like using test as the package name is a problem. It's already in use by the package containing the tests. I'll think of a solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
client Pull requests that update TypeScript code. (Added Automatically!) config-change Pull requests that change the config in a way that they require a deployment via Ansible. documentation plagiarism Pull requests that affect the corresponding module programming Pull requests that affect the corresponding module ready for review server Pull requests that update Java code. (Added Automatically!) stacked-pr PR that depends on another PR template tests
Projects
Status: Ready For Review
Status: In review
Development

Successfully merging this pull request may close these issues.

2 participants