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

feat: [#576] add package manager functionality #920

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

almas1992
Copy link
Contributor

@almas1992 almas1992 commented Feb 28, 2025

📑 Description

This feature introduces a package manager to handle the installation and uninstallation of packages within the framework. A setup folder is created in the package repository’s root directory, containing the setup.go file. The setup.go file handles key package management operations such as registering providers, adding configuration settings, and modifying Go files in the project.

The part of the package manager responsible for registering providers is automatically handled when creating a new package using the artisan make:package command. This ensures that the necessary providers are registered in the configuration files when installing a new package. For example, when installing the Redis package (github.com/goravel/redis), the ServiceProvider for Redis is added to config/app.go.

For example, using the Redis package (github.com/goravel/redis) as a case study, the package manager performs the following tasks:

  1. Installation Process:
  • It modifies the config/app.go file to register the Redis service provider, ensuring that Redis is available for use throughout the application.
  • It updates config/cache.go and config/queue.go to include necessary imports, configuration options, and Redis drivers, enabling caching and queue functionalities powered by Redis.
  1. Uninstallation Process:
  • It undoes the installation actions by removing the corresponding imports, provider registrations, and configurations from app.go, cache.go, and queue.go.

The installation and uninstallation processes are executed via command line, providing a simple and efficient way to manage packages. To install a package, run:

./artisan package:install github.com/goravel/redis

To uninstall the package, run:

./artisan package:uninstall github.com/goravel/redis

Additionally, the package manager supports a --force (-f) flag, which allows the installation process to proceed even if errors are encountered.

The setup.go file in the manager folder is responsible for managing the core functionality of the package manager. Below is the complete example code for the manager.go file:

package main

import (
	"os"
	"path/filepath"
	"runtime/debug"
	"strings"

	pkgcontracts "github.com/goravel/framework/contracts/packages"
	"github.com/goravel/framework/packages"
	"github.com/goravel/framework/support/color"
	"github.com/goravel/framework/support/path"
)

func main() {
	info, ok := debug.ReadBuildInfo()
	if !ok || !strings.HasSuffix(info.Path, "setup") {
		color.Errorln("Package module name is empty, please run command with module name.")
		return
	}
	module := filepath.Dir(info.Path)
	force := len(os.Args) == 3 && (os.Args[2] == "--force" || os.Args[2] == "-f")

	var pkg = &packages.Setup{
		Force:  force,
		Module: module,
		OnInstall: []pkgcontracts.FileModifier{
			packages.ModifyGoFile{
				File: path.Config("app.go"),
				Modifiers: []pkgcontracts.GoNodeModifier{
					packages.AddImportSpec(module),
					packages.AddProviderSpecBefore(
						"&redis.ServiceProvider{}",
						"&cache.ServiceProvider{}",
					),
				},
			},
			packages.ModifyGoFile{
				File: path.Config("cache.go"),
				Modifiers: []pkgcontracts.GoNodeModifier{
					packages.AddImportSpec("github.com/goravel/framework/contracts/cache"),
					packages.AddImportSpec("github.com/goravel/redis/facades", "redisfacades"),
					packages.AddConfigSpec("cache.stores", "redis", `
map[string]any{
        "driver": "custom",
        "connection": "default",
        "via": func() (cache.Driver, error) {
                return redisfacades.Cache("redis")
        },
}
`),
				},
			},
			packages.ModifyGoFile{
				File: path.Config("queue.go"),
				Modifiers: []pkgcontracts.GoNodeModifier{
					packages.AddImportSpec("github.com/goravel/framework/contracts/queue"),
					packages.AddImportSpec("github.com/goravel/redis/facades", "redisfacades"),
					packages.AddConfigSpec("queue.connections", "redis", `
map[string]any{
        "driver": "custom",
        "connection": "default",
        "via": func() (queue.Driver, error) {
                return redisfacades.Queue("redis")
        },
}`),
				},
			},
		},
		OnUninstall: []pkgcontracts.FileModifier{
			packages.ModifyGoFile{
				File: path.Config("app.go"),
				Modifiers: []pkgcontracts.GoNodeModifier{
					packages.RemoveImportSpec(module),
					packages.RemoveProviderSpec("&redis.ServiceProvider{}"),
				},
			},
			packages.ModifyGoFile{
				File: path.Config("cache.go"),
				Modifiers: []pkgcontracts.GoNodeModifier{
					packages.RemoveImportSpec("github.com/goravel/framework/contracts/cache"),
					packages.RemoveImportSpec("github.com/goravel/redis/facades", "redisfacades"),
					packages.RemoveConfigSpec("cache.stores.redis"),
				},
			},
			packages.ModifyGoFile{
				File: path.Config("queue.go"),
				Modifiers: []pkgcontracts.GoNodeModifier{
					packages.RemoveImportSpec("github.com/goravel/framework/contracts/queue"),
					packages.RemoveImportSpec("github.com/goravel/redis/facades", "redisfacades"),
					packages.RemoveConfigSpec("queue.connections.redis"),
				},
			},
		},
	}

	if len(os.Args) > 1 {
		execute(pkg, os.Args[1])
	}
}

func execute(pkg pkgcontracts.Setup, command string) {
	var err error
	switch command {
	case "install":
		err = pkg.Install()
	case "uninstall":
		err = pkg.Uninstall()
	default:
		return
	}

	if err != nil {
		color.Errorln(err)
		return
	}

	color.Successf("Package %sed successfully\n", command)
}
  1. Local Package Support

This feature also supports local package installation. For example, a local package can be created using:

./artisan make:package -m somepkg

Then, the package can be installed using the package manager:

./artisan package:install goravel/packages/somepkg

Closes goravel/goravel#576?

@coderabbitai summary

✅ Checks

  • Added test cases for my code

@almas1992 almas1992 requested a review from a team as a code owner February 28, 2025 09:56
Copy link
Contributor

coderabbitai bot commented Feb 28, 2025

Important

Review skipped

Auto reviews are limited to specific labels.

🏷️ Labels to auto review (1)
  • 🚀 Review Ready

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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 generate docstrings to generate docstrings for this 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 anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@almas1992 almas1992 marked this pull request as draft February 28, 2025 09:56
Copy link

codecov bot commented Feb 28, 2025

Codecov Report

Attention: Patch coverage is 71.71561% with 183 lines in your changes missing coverage. Please review.

Project coverage is 69.34%. Comparing base (f437993) to head (da055d8).
Report is 8 commits behind head on master.

Files with missing lines Patch % Lines
foundation/console/package_uninstall_command.go 0.00% 57 Missing ⚠️
foundation/console/package_install_command.go 0.00% 50 Missing ⚠️
packages/matcher.go 79.37% 33 Missing and 13 partials ⚠️
packages/setup.go 0.00% 16 Missing ⚠️
packages/modifier.go 89.09% 4 Missing and 2 partials ⚠️
packages/helper.go 97.52% 2 Missing and 1 partial ⚠️
support/console/execute.go 62.50% 2 Missing and 1 partial ⚠️
foundation/application.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #920      +/-   ##
==========================================
+ Coverage   69.14%   69.34%   +0.19%     
==========================================
  Files         158      168      +10     
  Lines       10607    11377     +770     
==========================================
+ Hits         7334     7889     +555     
- Misses       2942     3135     +193     
- Partials      331      353      +22     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: 72f4028 Previous: ab139f2 Ratio
BenchmarkFile_ReadWrite 332358 ns/op 2073 B/op 28 allocs/op 212688 ns/op 2072 B/op 28 allocs/op 1.56
BenchmarkFile_ReadWrite - ns/op 332358 ns/op 212688 ns/op 1.56

This comment was automatically generated by workflow using github-action-benchmark.

@almas1992 almas1992 marked this pull request as ready for review March 14, 2025 05:41
@almas1992 almas1992 marked this pull request as draft March 14, 2025 05:42
@almas1992 almas1992 force-pushed the almas/#576 branch 7 times, most recently from 0b08b3f to 2946b9b Compare March 20, 2025 07:47
@almas1992 almas1992 marked this pull request as ready for review March 20, 2025 07:48

Choose a reason for hiding this comment

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

Pull Request Overview

This PR introduces package manager functionality to support installation and uninstallation of packages, along with updates to console commands and helper functions for managing Go source modifications. Key changes include:

  • New console commands for package:install and package:uninstall.
  • Enhancements to package helper logic (modifiers, matchers, and tests) used in configuration and provider registration.
  • Updates to the package make command to support a new “manager” flag that generates the package manager files.

Reviewed Changes

Copilot reviewed 21 out of 22 changed files in this pull request and generated no comments.

Show a summary per file
File Description
foundation/console/package_uninstall_command.go Implements package uninstallation logic using Go commands.
foundation/console/package_install_command.go Implements package installation logic with version handling and tidying.
packages/* Introduces new helper, modifier, matcher functions and test cases.
foundation/console/package_make_command*.go Adds support for the “manager” flag and updates file generation logic.
foundation/application.go Registers new package management commands during application boot.
Files not reviewed (1)
  • go.mod: Language not supported
Comments suppressed due to low confidence (2)

foundation/console/package_make_command_test.go:45

  • [nitpick] The test error message for flag type assertions can be made more descriptive by clearly indicating whether the failure is for the manager flag or the root flag. This will help in debugging flag configuration issues.
managerFlag, ok := got.Flags[0].(*command.BoolFlag)

foundation/console/package_make_command.go:34

  • [nitpick] Consider enhancing the usage description for the 'manager' flag to more explicitly state its effect (for example, that it creates a manager folder with the necessary files) so that users immediately understand its functionality.
&command.BoolFlag{ Name: "manager", Aliases: []string{"m"}, Usage: "Create a package manager", DisableDefaultText: true, }
Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

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

Amazing PR 👍

Copy link
Contributor

Choose a reason for hiding this comment

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

Can we add some test cases for this file? Although It may be a bit complex.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I will add test case in new PR after merged this one.

Comment on lines 142 to 148
info, ok := debug.ReadBuildInfo()
if !ok || !strings.HasSuffix(info.Path, "setup") {
color.Errorln("Package module name is empty, please run command with module name.")
return
}
}
module := filepath.Dir(info.Path)
force := len(os.Args) == 3 && (os.Args[2] == "--force" || os.Args[2] == "-f")
Copy link
Contributor

Choose a reason for hiding this comment

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

Can these lines be moved to a common function of goravel/framework? There should only be a setup configuration in this file, reduce other code as much as possible. To avoid the problem of the code being changed in the future.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is to get the current package’s module name, i.e., import path. I’m not quite sure how to move it to the framework.

Copy link
Contributor

Choose a reason for hiding this comment

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

Let me make an example.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I have some thoughts on this. Let me try making some changes.

Comment on lines 175 to 197
if len(os.Args) > 1 {
execute(pkg, os.Args[1])
}
}
if len(os.Args) > 1 && os.Args[1] == "install" {
err := pkg.Install(dir)
if err != nil {
color.Errorln(err)
return
}
color.Successf("Package %s installed successfully\n", module)
func execute(pkg pkgcontracts.Setup, command string) {
var err error
switch command {
case "install":
err = pkg.Install()
case "uninstall":
err = pkg.Uninstall()
default:
return
}
if len(os.Args) > 1 && os.Args[1] == "uninstall" {
err := pkg.Uninstall(dir)
if err != nil {
color.Errorln(err)
return
}
color.Successf("Package %s uninstalled successfully\n", module)
if err != nil {
color.Errorln(err)
os.Exit(1)
}
}
color.Successf("Package %sed successfully\n", command)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ditto

@almas1992 almas1992 force-pushed the almas/#576 branch 3 times, most recently from 66aabcc to 446e763 Compare March 24, 2025 03:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enhanced Driver Selection and support customize facades during Project Initialization
2 participants