<commit_before>package updater

import (
	"fmt"
	log "github.com/Sirupsen/logrus"
	"github.com/blang/semver"
	"github.com/sabakaio/k8s-updater/pkg/registry"
	"k8s.io/kubernetes/pkg/api"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/labels"
	"strings"
)

// GetName returns the container name
func (c *Container) GetName() string {
	return c.container.Name
}

// GetImageName returns the container image name
func (c *Container) GetImageName() string {
	return c.container.Image
}

// ParseImageVersion return semver of current container image
func (c *Container) ParseImageVersion() (semver.Version, error) {
	image := strings.Split(c.container.Image, ":")
	if len(image) != 2 {
		return semver.Version{}, fmt.Errorf(
			"invalid image name, could not extract version: %s", c.container.Image)
	}
	return semver.ParseTolerant(image[1])
}

// UpdateImageVersion updates Deployment template with the set version. It does nto save the deployment.
func (c *Container) UpdateImageVersion(v semver.Version) (*Container, error) {
	image := strings.Split(c.container.Image, ":")
	if len(image) != 2 {
		return c, fmt.Errorf(
			"invalid image name, could not extract version: %s", c.container.Image)
	}
	stringVersion := v.String()
	imageString := strings.Join([]string{image[0], stringVersion}, ":")
	c.deployment.Spec.Template.Spec.Containers[c.containerKey].Image = imageString
	return c, nil
}

// GetLatestVersion returns a latest image version from repository
func (c *Container) GetLatestVersion() (semver.Version, error) {
	return c.repository.GetLatestVersion()
}

// NewList list containers to check for updates
func NewList(k *client.Client, namespace string) (containers *ContainerList, err error) {
	// List all deployments lebled with `autoupdate`
	selector, err := labels.Parse("autoupdate")
	if err != nil {
		return
	}
	opts := api.ListOptions{
		LabelSelector: selector,
	}
	deployments, err := k.Deployments(namespace).List(opts)
	if err != nil {
		return
	}

	// Iterate over the list of deployments to get a list of containers
	containers = new(ContainerList)
	for _, d := range deployments.Items {
		// Get deployment spec registries
		registries, e := registry.GetRegistries(k, &d)
		if e != nil {
			err = e
			return
		}
		// Iterate over pod containers to get update targets
		for _, c := range d.Spec.Template.Spec.Containers {
			var container = &Container{
				container:    &c,
				deployment:   &d,
				containerKey: i,
			}
			image := container.GetImageName()
			// Choose a registry for container by the name
			for _, r := range registries.Items {
				if strings.HasPrefix(image, r.Name+"/") {
					container.repository = registry.NewRepository(image, r)
					break
				}
			}
			if container.repository == nil {
				if defaultRegistry, err := registries.Get("default"); err == nil {
					container.repository = registry.NewRepository(image, defaultRegistry)
				} else {
					log.Errorf("container '%s' of deployment '%s' has no private registry configured", c.Name, d.Name)
					continue
				}
			}
			log.Debugf("container '%s' of deployment '%s' uses '%s' repository", c.Name, d.Name, container.repository.Name)
			containers.Items = append(containers.Items, container)
		}
	}

	return
}

func (c *Container) UpdateDeployment(k *client.Client, namespace string, v semver.Version) error {
	newContainer, err := c.UpdateImageVersion(v)
	if err != nil {
		return err
	}

	newDeployment, err := k.Deployments(namespace).Update(newContainer.deployment)
	fmt.Println(newDeployment.GetName())
	// TODO: what to do with the new deployment? Update our memory store?

	if err != nil {
		return err
	}
<commit_msg>fn comment<commit_after>package updater

import (
	"fmt"
	log "github.com/Sirupsen/logrus"
	"github.com/blang/semver"
	"github.com/sabakaio/k8s-updater/pkg/registry"
	"k8s.io/kubernetes/pkg/api"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/labels"
	"strings"
)

// GetName returns the container name
func (c *Container) GetName() string {
	return c.container.Name
}

// GetImageName returns the container image name
func (c *Container) GetImageName() string {
	return c.container.Image
}

// ParseImageVersion return semver of current container image
func (c *Container) ParseImageVersion() (semver.Version, error) {
	image := strings.Split(c.container.Image, ":")
	if len(image) != 2 {
		return semver.Version{}, fmt.Errorf(
			"invalid image name, could not extract version: %s", c.container.Image)
	}
	return semver.ParseTolerant(image[1])
}

// UpdateImageVersion updates Deployment template with the set version. It does nto save the deployment.
func (c *Container) UpdateImageVersion(v semver.Version) (*Container, error) {
	image := strings.Split(c.container.Image, ":")
	if len(image) != 2 {
		return c, fmt.Errorf(
			"invalid image name, could not extract version: %s", c.container.Image)
	}
	stringVersion := v.String()
	imageString := strings.Join([]string{image[0], stringVersion}, ":")
	c.deployment.Spec.Template.Spec.Containers[c.containerKey].Image = imageString
	return c, nil
}

// GetLatestVersion returns a latest image version from repository
func (c *Container) GetLatestVersion() (semver.Version, error) {
	return c.repository.GetLatestVersion()
}

// NewList list containers to check for updates
func NewList(k *client.Client, namespace string) (containers *ContainerList, err error) {
	// List all deployments lebled with `autoupdate`
	selector, err := labels.Parse("autoupdate")
	if err != nil {
		return
	}
	opts := api.ListOptions{
		LabelSelector: selector,
	}
	deployments, err := k.Deployments(namespace).List(opts)
	if err != nil {
		return
	}

	// Iterate over the list of deployments to get a list of containers
	containers = new(ContainerList)
	for _, d := range deployments.Items {
		// Get deployment spec registries
		registries, e := registry.GetRegistries(k, &d)
		if e != nil {
			err = e
			return
		}
		// Iterate over pod containers to get update targets
		for _, c := range d.Spec.Template.Spec.Containers {
			var container = &Container{
				container:    &c,
				deployment:   &d,
				containerKey: i,
			}
			image := container.GetImageName()
			// Choose a registry for container by the name
			for _, r := range registries.Items {
				if strings.HasPrefix(image, r.Name+"/") {
					container.repository = registry.NewRepository(image, r)
					break
				}
			}
			if container.repository == nil {
				if defaultRegistry, err := registries.Get("default"); err == nil {
					container.repository = registry.NewRepository(image, defaultRegistry)
				} else {
					log.Errorf("container '%s' of deployment '%s' has no private registry configured", c.Name, d.Name)
					continue
				}
			}
			log.Debugf("container '%s' of deployment '%s' uses '%s' repository", c.Name, d.Name, container.repository.Name)
			containers.Items = append(containers.Items, container)
		}
	}

	return
}

// UpdateDeployment updates Deployment version on the cluster
func (c *Container) UpdateDeployment(k *client.Client, namespace string, v semver.Version) error {
	newContainer, err := c.UpdateImageVersion(v)
	if err != nil {
		return err
	}

	newDeployment, err := k.Deployments(namespace).Update(newContainer.deployment)
	fmt.Println(newDeployment.GetName())
	// TODO: what to do with the new deployment? Update our memory store?

	if err != nil {
		return err
	}

{'fraction_non_alphanumeric': 0.12325612894487335, 'fraction_numerical': 0.00216714072870107, 'mean_word_length': 3.995940460081191, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4006819', 'n_tokens_mistral': 2518, 'n_tokens_neox': 2321, 'n_words': 664}