diff --git a/cmd/cmd.go b/cmd/cmd.go index d9bd9b1..577f5ac 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -161,7 +161,7 @@ func initializedRootFromArgs(stdout, stderr io.Writer, args []string) (*cobra.Co rootCmd.AddCommand(newExtCmd()) if err := addExtensions(rootCmd); err != nil { - return nil, nil, fmt.Errorf("failed to register extensions: %w", err) + uii.Verboseln("failed to register extensions: %s", err.Error()) } if isInRepoContext() { diff --git a/cmd/ext.go b/cmd/ext.go index f240b8e..5e5ed24 100644 --- a/cmd/ext.go +++ b/cmd/ext.go @@ -50,8 +50,8 @@ func addExtensions(rootCmd *cobra.Command) error { Version: extension.Version(), GroupID: "extensions", DisableFlagParsing: true, - RunE: func(cmd *cobra.Command, args []string) error { + RunE: func(cmd *cobra.Command, args []string) error { extCmd := exec.CommandContext(cmd.Context(), extension.FullPath(), args...) extCmd.Stdout = os.Stdout @@ -87,6 +87,7 @@ func newExtCmd() *cobra.Command { newExtInstallCmd(globalConfig), newExtUpdateCmd(globalConfig), newExtInitCmd(globalConfig), + newExtPublishCmd(globalConfig), ) cmd.PersistentFlags().StringVar(&globalConfig.registry, "registry", "", "the given registry, if not set will default to SHUTTLE_EXTENSIONS_REGISTRY") @@ -146,3 +147,26 @@ func newExtInitCmd(globalConfig *extGlobalConfig) *cobra.Command { return cmd } + +func newExtPublishCmd(globalConfig *extGlobalConfig) *cobra.Command { + var version string + + cmd := &cobra.Command{ + Use: "publish", + Short: "Publishes the current extension to a registry", + RunE: func(cmd *cobra.Command, args []string) error { + extManager := extensions.NewExtensionsManager(global.NewGlobalStore()) + + if err := extManager.Publish(cmd.Context(), version); err != nil { + return err + } + + return nil + }, + } + + cmd.Flags().StringVar(&version, "version", "", "the version to publish") + cmd.MarkFlagRequired("version") + + return cmd +} diff --git a/internal/extensions/downloader.go b/internal/extensions/downloader.go index dc3f74c..9239f56 100644 --- a/internal/extensions/downloader.go +++ b/internal/extensions/downloader.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "log" "net/http" "os" "time" @@ -54,11 +55,16 @@ func (d *gitHubReleaseDownloader) Download(ctx context.Context, dest string) err } defer resp.Body.Close() + if err := os.RemoveAll(dest); err != nil { + log.Printf("failed to remove extension before downloading new: %s", err.Error()) + } + extensionBinary, err := os.Create(dest) if err != nil { return err } defer extensionBinary.Close() + extensionBinary.Chmod(0o755) if _, err := io.Copy(extensionBinary, resp.Body); err != nil { return err diff --git a/internal/extensions/extension.go b/internal/extensions/extension.go index f1f6ae5..c79a90c 100644 --- a/internal/extensions/extension.go +++ b/internal/extensions/extension.go @@ -39,7 +39,8 @@ func (e *Extension) Ensure(ctx context.Context) error { binaryPath := path.Join(extensionsCachePath, binaryName) if exists(binaryPath) { - return nil + // TODO: do a checksum chck + //return nil } downloadLink := e.getRemoteBinaryDownloadLink() diff --git a/internal/extensions/extension_source.go b/internal/extensions/extension_source.go new file mode 100644 index 0000000..d9727f8 --- /dev/null +++ b/internal/extensions/extension_source.go @@ -0,0 +1,44 @@ +package extensions + +import ( + "context" + "fmt" + "os" + + "gopkg.in/yaml.v2" +) + +type shuttleExtensionsRegistry struct { + GitHub *string `json:"github" yaml:"github"` +} + +type shuttleExtensionProviderGitHubRelease struct { + Owner string `json:"owner" yaml:"owner"` + Repo string `json:"repo" yaml:"repo"` +} + +type shuttleExtensionsProvider struct { + GitHubRelease *shuttleExtensionProviderGitHubRelease `json:"github-release" yaml:"github-release"` +} + +type shuttleExtensionsFile struct { + Name string `json:"name" yaml:"name"` + Description string `json:"description" yaml:"description"` + + Provider shuttleExtensionsProvider `json:"provider" yaml:"provider"` + Registry shuttleExtensionsRegistry `json:"registry" yaml:"registry"` +} + +func getExtensionsFile(ctx context.Context) (*shuttleExtensionsFile, error) { + templateFileContent, err := os.ReadFile("shuttle.template.yaml") + if err != nil { + return nil, fmt.Errorf("failed to find shuttle.template.yaml: %w", err) + } + + var templateFile shuttleExtensionsFile + if err := yaml.Unmarshal(templateFileContent, &templateFile); err != nil { + return nil, fmt.Errorf("failed to parse shuttle.template.yaml: %w", err) + } + + return &templateFile, nil +} diff --git a/internal/extensions/extensions.go b/internal/extensions/extensions.go index 4ddf066..1260f4b 100644 --- a/internal/extensions/extensions.go +++ b/internal/extensions/extensions.go @@ -76,7 +76,7 @@ func (e *ExtensionsManager) Install(ctx context.Context) error { // Update will fetch the latest extensions from a registry and install them afterwards so that they're ready for use func (e *ExtensionsManager) Update(ctx context.Context, registry string) error { - reg, err := NewRegistry(registry, e.globalStore) + reg, err := NewRegistryFromCombined(registry, e.globalStore) if err != nil { return fmt.Errorf("failed to update extensions: %w", err) } @@ -91,3 +91,21 @@ func (e *ExtensionsManager) Update(ctx context.Context, registry string) error { return nil } + +func (e *ExtensionsManager) Publish(ctx context.Context, version string) error { + extensionsFile, err := getExtensionsFile(ctx) + if err != nil { + return err + } + + registry, err := NewRegistry("github", "", e.globalStore) + if err != nil { + return err + } + + if err := registry.Publish(ctx, extensionsFile, version); err != nil { + return err + } + + return nil +} diff --git a/internal/extensions/git_registry.go b/internal/extensions/git_registry.go index 6958bfa..748de3a 100644 --- a/internal/extensions/git_registry.go +++ b/internal/extensions/git_registry.go @@ -16,6 +16,11 @@ type gitRegistry struct { globalStore *global.GlobalStore } +// Publish isn't implemented yet for gitRegistry +func (*gitRegistry) Publish(ctx context.Context, extFile *shuttleExtensionsFile, version string) error { + panic("unimplemented") +} + func (*gitRegistry) Get(ctx context.Context) error { panic("unimplemented") } diff --git a/internal/extensions/github_registry.go b/internal/extensions/github_registry.go new file mode 100644 index 0000000..d1b23bb --- /dev/null +++ b/internal/extensions/github_registry.go @@ -0,0 +1,330 @@ +package extensions + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "os" + "strings" +) + +type gitHubRegistry struct { + client *githubClient +} + +func (g *gitHubRegistry) Publish(ctx context.Context, extFile *shuttleExtensionsFile, version string) error { + release, err := g.client.GetRelease(ctx, extFile, version) + if err != nil { + return err + } + + sha, err := g.client.GetFile(ctx, extFile) + if err != nil { + log.Printf("failed to find file: %s", err.Error()) + // Ignore file as it probably means that the file wasn't there + } + + if err := g.client.UpsertFile(ctx, extFile, release, version, sha); err != nil { + return err + } + + log.Println("done") + return nil +} + +// Get isn't implemented yet for GitHubRegistry +func (*gitHubRegistry) Get(ctx context.Context) error { + panic("unimplemented") +} + +// Update isn't implemented yet for GitHubRegistry +func (*gitHubRegistry) Update(ctx context.Context) error { + panic("unimplemented") +} + +func newGitHubRegistry() (Registry, error) { + client, err := newGitHubClient() + if err != nil { + return nil, err + } + + return &gitHubRegistry{ + client: client, + }, nil +} + +type githubClient struct { + accessToken string + httpClient *http.Client +} + +func newGitHubClient() (*githubClient, error) { + var token string + if accessToken := os.Getenv("SHUTTLE_EXTENSIONS_GITHUB_ACCESS_TOKEN"); accessToken != "" { + token = accessToken + } else if accessToken := os.Getenv("GITHUB_ACCESS_TOKEN"); accessToken != "" { + token = accessToken + } + + if token == "" { + return nil, errors.New("GITHUB_ACCESS_TOKEN was not set") + } + + return &githubClient{ + accessToken: token, + httpClient: http.DefaultClient, + }, nil +} + +func (gc *githubClient) GetFile(ctx context.Context, shuttleExtensionsFile *shuttleExtensionsFile) (string, error) { + owner, repo, ok := strings.Cut(*shuttleExtensionsFile.Registry.GitHub, "/") + if !ok { + return "", fmt.Errorf("failed to find owner and repo in registry: %s", *shuttleExtensionsFile.Registry.GitHub) + } + + extensionsFile, err := githubClientDo[any, githubFileShaResp]( + ctx, + gc, + http.MethodGet, + fmt.Sprintf( + "/repos/%s/%s/contents/%s", + owner, + repo, + getRemoteRegistryExtensionPathFile(shuttleExtensionsFile.Name), + ), + nil, + ) + if err != nil { + return "", err + } + + return extensionsFile.Sha, nil +} + +func (gc *githubClient) UpsertFile(ctx context.Context, shuttleExtensionsFile *shuttleExtensionsFile, releaseInformation *githubReleaseInformation, version string, sha string) error { + registryExtensionsReq := registryExtension{ + Name: shuttleExtensionsFile.Name, + Description: shuttleExtensionsFile.Description, + Version: version, + DownloadUrls: make([]registryExtensionDownloadLink, 0), + } + + for _, releaseAsset := range releaseInformation.Assets { + arch, os, err := releaseAsset.ParseDownloadLink(shuttleExtensionsFile.Name) + if err != nil { + log.Printf("file did not match an actual binary: %s, %s", releaseAsset.DownloadUrl, err.Error()) + continue + } + + downloadLink := registryExtensionDownloadLink{ + Architecture: arch, + Os: os, + Url: releaseAsset.DownloadUrl, + Provider: "github-release", + } + + registryExtensionsReq.DownloadUrls = append(registryExtensionsReq.DownloadUrls, downloadLink) + } + + upsertRequest, err := newGitHubUpsertRequest( + shuttleExtensionsFile.Name, + version, + registryExtensionsReq, + sha, + ) + if err != nil { + return err + } + + owner, repo, ok := strings.Cut(*shuttleExtensionsFile.Registry.GitHub, "/") + if !ok { + return fmt.Errorf("failed to find owner and repo in registry: %s", *shuttleExtensionsFile.Registry.GitHub) + } + + _, err = githubClientDo[githubUpsertFileRequest, any]( + ctx, + gc, + http.MethodPut, + fmt.Sprintf( + "/repos/%s/%s/contents/%s", + owner, + repo, + getRemoteRegistryExtensionPathFile(shuttleExtensionsFile.Name), + ), + upsertRequest, + ) + if err != nil { + return err + } + + return nil +} + +func (gc *githubClient) GetRelease(ctx context.Context, shuttleExtensionsFile *shuttleExtensionsFile, version string) (*githubReleaseInformation, error) { + release, err := githubClientDo[any, githubReleaseInformation]( + ctx, + gc, + http.MethodGet, + fmt.Sprintf( + "/repos/%s/%s/releases/tags/%s", + shuttleExtensionsFile.Provider.GitHubRelease.Owner, + shuttleExtensionsFile.Provider.GitHubRelease.Repo, + version, + ), + nil, + ) + if err != nil { + return nil, err + } + + if len(release.Assets) == 0 { + return nil, errors.New("found no releases for github release") + } + + return release, nil +} + +type githubReleaseAsset struct { + DownloadUrl string `json:"browser_download_url"` +} + +func (gra *githubReleaseAsset) ParseDownloadLink(name string) (arch string, os string, err error) { + components := strings.Split(gra.DownloadUrl, "/") + if len(components) < 3 { + return "", "", errors.New("failed to find a proper github download link") + } + + file := components[len(components)-1] + + rest, ok := strings.CutPrefix(file, name) + if !ok { + return "", "", errors.New("file link did not contain extension name") + } + rest = strings.TrimPrefix(rest, "-") + + os, arch, ok = strings.Cut(rest, "-") + if !ok { + return "", "", errors.New("file did not match os-arch") + } + + return arch, os, nil +} + +type githubReleaseInformation struct { + Assets []githubReleaseAsset `json:"assets"` +} + +type githubFileShaResp struct { + Sha string `json:"sha"` +} + +type githubCommitter struct { + Name string `json:"name"` + Email string `json:"email"` +} + +type githubUpsertFileRequest struct { + Message string `json:"message"` + Committer githubCommitter `json:"committer"` + Content string `json:"content"` + Sha *string `json:"sha"` +} + +func newGitHubUpsertRequest(name string, version string, registryExtensionsReq registryExtension, sha string) (*githubUpsertFileRequest, error) { + committerName := os.Getenv("GITHUB_COMMITTER_NAME") + if committerName == "" { + return nil, errors.New("GITHUB_COMMITTER_NAME was not found") + } + + committerEmail := os.Getenv("GITHUB_COMMITTER_EMAIL") + if committerEmail == "" { + return nil, errors.New("GITHUB_COMMITTER_EMAIL was not found") + } + + content, err := json.MarshalIndent(registryExtensionsReq, "", " ") + if err != nil { + return nil, err + } + + contentB64 := base64.StdEncoding.EncodeToString(content) + + req := &githubUpsertFileRequest{ + Message: fmt.Sprintf("chore(extensions): updating %s to %s", name, version), + Committer: githubCommitter{ + Name: committerName, + Email: committerEmail, + }, + Content: contentB64, + } + + if sha != "" { + req.Sha = &sha + } + + return req, nil +} + +func githubClientDo[TReq any, TResp any](ctx context.Context, githubClient *githubClient, method string, path string, reqBody *TReq) (*TResp, error) { + var bodyReader io.Reader + if reqBody != nil { + contents, err := json.Marshal(reqBody) + if err != nil { + return nil, err + } + + bodyReader = bytes.NewReader(contents) + } + + url := fmt.Sprintf("https://api.github.com/%s", strings.TrimPrefix(path, "/")) + + req, err := http.NewRequestWithContext( + ctx, + method, + url, + bodyReader, + ) + if err != nil { + return nil, err + } + + req.Header.Add("Accept", "application/vnd.github+json") + req.Header.Add("X-GitHub-Api-Version", "2022-11-28") + req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", githubClient.accessToken)) + + resp, err := githubClient.httpClient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + respContent, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + if resp.StatusCode > 399 { + var message githubMessage + if err := json.Unmarshal(respContent, &message); err != nil { + return nil, fmt.Errorf("failed to unmarshal resp: %w", err) + } + + return nil, fmt.Errorf("failed github request with: %s", message.Message) + } + + var returnObject TResp + if err := json.Unmarshal(respContent, &returnObject); err != nil { + return nil, err + } + + return &returnObject, nil +} + +type githubMessage struct { + Message string `json:"message"` +} diff --git a/internal/extensions/registry.go b/internal/extensions/registry.go index 13fcf21..5edcd49 100644 --- a/internal/extensions/registry.go +++ b/internal/extensions/registry.go @@ -12,10 +12,11 @@ import ( type Registry interface { Get(ctx context.Context) error Update(ctx context.Context) error + Publish(ctx context.Context, extFile *shuttleExtensionsFile, version string) error } -// NewRegistry is a shim for concrete implementations of the registries, such as gitRegistry -func NewRegistry(registry string, globalStore *global.GlobalStore) (Registry, error) { +// NewRegistryFromCombined is a shim for concrete implementations of the registries, such as gitRegistry +func NewRegistryFromCombined(registry string, globalStore *global.GlobalStore) (Registry, error) { registryType, registryUrl, ok := strings.Cut(registry, "=") if !ok { return nil, fmt.Errorf("registry was not a valid url: %s", registry) @@ -28,3 +29,15 @@ func NewRegistry(registry string, globalStore *global.GlobalStore) (Registry, er return nil, fmt.Errorf("registry type was not valid: %s", registryType) } } + +// NewRegistry is a shim for concrete implementations of the registries, such as gitRegistry +func NewRegistry(registryType string, registryUrl string, globalStore *global.GlobalStore) (Registry, error) { + switch registryType { + case "git": + return newGitRegistry(registryUrl, globalStore), nil + case "github": + return newGitHubRegistry() + default: + return nil, fmt.Errorf("registry type was not valid: %s", registryType) + } +} diff --git a/internal/extensions/remote_registry.go b/internal/extensions/remote_registry.go new file mode 100644 index 0000000..febb62e --- /dev/null +++ b/internal/extensions/remote_registry.go @@ -0,0 +1,9 @@ +package extensions + +import "context" + +type RemoteRegistry interface { + Publish(ctx context.Context) error +} + +func NewRemoteRegistry(registry string) {} diff --git a/internal/extensions/remote_registry_paths.go b/internal/extensions/remote_registry_paths.go new file mode 100644 index 0000000..fbfc180 --- /dev/null +++ b/internal/extensions/remote_registry_paths.go @@ -0,0 +1,15 @@ +package extensions + +import "path" + +func getRemoteRegistryIndex() string { + return "index" +} + +func getRemoteRegistryExtensionPath(name string) string { + return path.Join(getRemoteRegistryIndex(), name) +} + +func getRemoteRegistryExtensionPathFile(name string) string { + return path.Join(getRemoteRegistryExtensionPath(name), "shuttle-extension.json") +}