pkg_install.go 2 KB
Newer Older
bryanl's avatar
bryanl committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Copyright 2018 The ksonnet authors
//
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

package actions

import (
bryanl's avatar
bryanl committed
19
	"github.com/ksonnet/ksonnet/pkg/app"
bryanl's avatar
bryanl committed
20 21 22 23 24 25 26 27
	"github.com/ksonnet/ksonnet/pkg/pkg"
	"github.com/ksonnet/ksonnet/pkg/registry"
)

// DepCacher is a function that caches a dependency.j
type DepCacher func(app.App, pkg.Descriptor, string) error

// RunPkgInstall runs `pkg install`
bryanl's avatar
bryanl committed
28 29
func RunPkgInstall(m map[string]interface{}) error {
	pi, err := NewPkgInstall(m)
bryanl's avatar
bryanl committed
30 31 32 33 34 35 36
	if err != nil {
		return err
	}

	return pi.Run()
}

37
// PkgInstall installs packages.
bryanl's avatar
bryanl committed
38
type PkgInstall struct {
bryanl's avatar
bryanl committed
39 40 41 42
	app         app.App
	libName     string
	customName  string
	depCacherFn DepCacher
bryanl's avatar
bryanl committed
43 44 45
}

// NewPkgInstall creates an instance of PkgInstall.
bryanl's avatar
bryanl committed
46 47 48
func NewPkgInstall(m map[string]interface{}) (*PkgInstall, error) {
	ol := newOptionLoader(m)

bryanl's avatar
bryanl committed
49
	nl := &PkgInstall{
bryanl's avatar
bryanl committed
50 51 52
		app:        ol.LoadApp(),
		libName:    ol.LoadString(OptionLibName),
		customName: ol.LoadString(OptionName),
bryanl's avatar
bryanl committed
53 54

		depCacherFn: registry.CacheDependency,
bryanl's avatar
bryanl committed
55 56
	}

bryanl's avatar
bryanl committed
57 58
	if ol.err != nil {
		return nil, ol.err
bryanl's avatar
bryanl committed
59 60 61 62 63
	}

	return nl, nil
}

64
// Run installs packages.
bryanl's avatar
bryanl committed
65 66 67 68 69 70
func (pi *PkgInstall) Run() error {
	d, customName, err := pi.parseDepSpec()
	if err != nil {
		return err
	}

bryanl's avatar
bryanl committed
71
	return pi.depCacherFn(pi.app, d, customName)
bryanl's avatar
bryanl committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
}

func (pi *PkgInstall) parseDepSpec() (pkg.Descriptor, string, error) {
	d, err := pkg.ParseName(pi.libName)
	if err != nil {
		return pkg.Descriptor{}, "", err
	}

	customName := pi.customName
	if customName == "" {
		customName = d.Part
	}

	return d, customName, nil
}