Merge pull request #12 from brancz/lock

Respect lock-file and add update command
This commit is contained in:
Frederic Branczyk 2018-07-25 20:01:05 +02:00 committed by GitHub
commit e2bf71cd8e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 192 additions and 35 deletions

View file

@ -17,7 +17,27 @@ All command line flags:
[embedmd]:# (_output/help.txt) [embedmd]:# (_output/help.txt)
```txt ```txt
$ jb -h $ jb -h
Usage of jb: usage: jb [<flags>] <command> [<args> ...]
-jsonnetpkg-home string
The directory used to cache packages in. (default "vendor") A jsonnet package manager
Flags:
-h, --help Show context-sensitive help (also try --help-long and --help-man).
--jsonnetpkg-home="vendor"
The directory used to cache packages in.
Commands:
help [<command>...]
Show help.
init
Initialize a new empty jsonnetfile
install [<packages>...]
Install all dependencies or install specific ones
update
Update all dependencies.
``` ```

View file

@ -35,6 +35,7 @@ import (
const ( const (
installActionName = "install" installActionName = "install"
updateActionName = "update"
initActionName = "init" initActionName = "init"
basePath = ".jsonnetpkg" basePath = ".jsonnetpkg"
srcDirName = "src" srcDirName = "src"
@ -76,6 +77,8 @@ func Main() int {
installCmd := a.Command(installActionName, "Install all dependencies or install specific ones") installCmd := a.Command(installActionName, "Install all dependencies or install specific ones")
installCmdURLs := installCmd.Arg("packages", "URLs to package to install").URLList() installCmdURLs := installCmd.Arg("packages", "URLs to package to install").URLList()
updateCmd := a.Command(updateActionName, "Update all dependencies.")
command, err := a.Parse(os.Args[1:]) command, err := a.Parse(os.Args[1:])
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, errors.Wrapf(err, "Error parsing commandline arguments")) fmt.Fprintln(os.Stderr, errors.Wrapf(err, "Error parsing commandline arguments"))
@ -88,6 +91,8 @@ func Main() int {
return initCommand() return initCommand()
case installCmd.FullCommand(): case installCmd.FullCommand():
return installCommand(cfg.JsonnetHome, *installCmdURLs...) return installCommand(cfg.JsonnetHome, *installCmdURLs...)
case updateCmd.FullCommand():
return updateCommand(cfg.JsonnetHome)
default: default:
installCommand(cfg.JsonnetHome) installCommand(cfg.JsonnetHome)
} }
@ -220,7 +225,21 @@ func parseGithubDependency(urlString string) *spec.Dependency {
} }
func installCommand(jsonnetHome string, urls ...*url.URL) int { func installCommand(jsonnetHome string, urls ...*url.URL) int {
m, err := pkg.LoadJsonnetfile(pkg.JsonnetFile) workdir := "."
useLock, err := pkg.LockExists(workdir)
if err != nil {
kingpin.Fatalf("failed to check if jsonnetfile.lock.json exists: %v", err)
return 1
}
jsonnetfile, err := pkg.ChooseJsonnetFile(workdir)
if err != nil {
kingpin.Fatalf("failed to choose jsonnetfile: %v", err)
return 1
}
m, err := pkg.LoadJsonnetfile(jsonnetfile)
if err != nil { if err != nil {
kingpin.Fatalf("failed to load jsonnetfile: %v", err) kingpin.Fatalf("failed to load jsonnetfile: %v", err)
return 1 return 1
@ -269,12 +288,14 @@ func installCommand(jsonnetHome string, urls ...*url.URL) int {
return 3 return 3
} }
lock, err := pkg.Install(context.TODO(), m, jsonnetHome) lock, err := pkg.Install(context.TODO(), jsonnetfile, m, jsonnetHome)
if err != nil { if err != nil {
kingpin.Fatalf("failed to install: %v", err) kingpin.Fatalf("failed to install: %v", err)
return 3 return 3
} }
// If installing from lock file there is no need to write any files back.
if !useLock {
b, err := json.MarshalIndent(m, "", " ") b, err := json.MarshalIndent(m, "", " ")
if err != nil { if err != nil {
kingpin.Fatalf("failed to encode jsonnet file: %v", err) kingpin.Fatalf("failed to encode jsonnet file: %v", err)
@ -298,6 +319,43 @@ func installCommand(jsonnetHome string, urls ...*url.URL) int {
kingpin.Fatalf("failed to write lock file: %v", err) kingpin.Fatalf("failed to write lock file: %v", err)
return 3 return 3
} }
}
return 0
}
func updateCommand(jsonnetHome string, urls ...*url.URL) int {
jsonnetfile := pkg.JsonnetFile
m, err := pkg.LoadJsonnetfile(jsonnetfile)
if err != nil {
kingpin.Fatalf("failed to load jsonnetfile: %v", err)
return 1
}
err = os.MkdirAll(jsonnetHome, os.ModePerm)
if err != nil {
kingpin.Fatalf("failed to create jsonnet home path: %v", err)
return 3
}
lock, err := pkg.Install(context.TODO(), jsonnetfile, m, jsonnetHome)
if err != nil {
kingpin.Fatalf("failed to install: %v", err)
return 3
}
b, err := json.MarshalIndent(lock, "", " ")
if err != nil {
kingpin.Fatalf("failed to encode jsonnet file: %v", err)
return 3
}
err = ioutil.WriteFile(pkg.JsonnetLockFile, b, 0644)
if err != nil {
kingpin.Fatalf("failed to write lock file: %v", err)
return 3
}
return 0 return 0
} }

View file

@ -33,7 +33,7 @@ var (
VersionMismatch = errors.New("multiple colliding versions specified") VersionMismatch = errors.New("multiple colliding versions specified")
) )
func Install(ctx context.Context, m spec.JsonnetFile, dir string) (lock *spec.JsonnetFile, err error) { func Install(ctx context.Context, dependencySourceIdentifier string, m spec.JsonnetFile, dir string) (lock *spec.JsonnetFile, err error) {
lock = &spec.JsonnetFile{} lock = &spec.JsonnetFile{}
for _, dep := range m.Dependencies { for _, dep := range m.Dependencies {
tmp := filepath.Join(dir, ".tmp") tmp := filepath.Join(dir, ".tmp")
@ -58,11 +58,11 @@ func Install(ctx context.Context, m spec.JsonnetFile, dir string) (lock *spec.Js
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to install package") return nil, errors.Wrap(err, "failed to install package")
} }
// need to deduplicate/error when multiple entries
lock.Dependencies, err = insertDependency(lock.Dependencies, spec.Dependency{ lock.Dependencies, err = insertDependency(lock.Dependencies, spec.Dependency{
Name: dep.Name, Name: dep.Name,
Source: dep.Source, Source: dep.Source,
Version: lockVersion, Version: lockVersion,
DepSource: dependencySourceIdentifier,
}) })
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to insert dependency to lock dependencies") return nil, errors.Wrap(err, "failed to insert dependency to lock dependencies")
@ -87,13 +87,18 @@ func Install(ctx context.Context, m spec.JsonnetFile, dir string) (lock *spec.Js
return nil, errors.Wrap(err, "failed to move package") return nil, errors.Wrap(err, "failed to move package")
} }
if _, err := os.Stat(path.Join(destPath, JsonnetFile)); !os.IsNotExist(err) { filepath, err := ChooseJsonnetFile(destPath)
depsDeps, err := LoadJsonnetfile(path.Join(destPath, JsonnetFile))
if err != nil { if err != nil {
return nil, err return nil, err
} }
depsDeps, err := LoadJsonnetfile(filepath)
// It is ok for depedencies not to have a JsonnetFile, it just means
// they do not have transitive dependencies of their own.
if err != nil && !os.IsNotExist(err) {
return nil, err
}
depsInstalledByDependency, err := Install(ctx, depsDeps, dir) depsInstalledByDependency, err := Install(ctx, filepath, depsDeps, dir)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -105,7 +110,6 @@ func Install(ctx context.Context, m spec.JsonnetFile, dir string) (lock *spec.Js
} }
} }
} }
}
return lock, nil return lock, nil
} }
@ -116,24 +120,63 @@ func insertDependency(deps []spec.Dependency, newDep spec.Dependency) ([]spec.De
} }
res := []spec.Dependency{} res := []spec.Dependency{}
newDepPreviouslyPresent := false
for _, d := range deps { for _, d := range deps {
if d.Name == newDep.Name { if d.Name == newDep.Name {
if d.Version != newDep.Version { if d.Version != newDep.Version {
return nil, VersionMismatch return nil, fmt.Errorf("multiple colliding versions specified for %s: %s (from %s) and %s (from %s)", d.Name, d.Version, d.DepSource, newDep.Version, newDep.DepSource)
} }
res = append(res, d) res = append(res, d)
newDepPreviouslyPresent = true
} else { } else {
res = append(res, d) res = append(res, d)
} }
} }
if !newDepPreviouslyPresent {
res = append(res, newDep)
}
return res, nil return res, nil
} }
func LoadJsonnetfile(filename string) (spec.JsonnetFile, error) { func LockExists(dir string) (bool, error) {
lockfile := path.Join(dir, JsonnetLockFile)
_, err := os.Stat(lockfile)
if os.IsNotExist(err) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
func ChooseJsonnetFile(dir string) (string, error) {
lockfile := path.Join(dir, JsonnetLockFile)
jsonnetfile := path.Join(dir, JsonnetFile)
filename := lockfile
lockExists, err := LockExists(dir)
if err != nil {
return "", err
}
if !lockExists {
filename = jsonnetfile
}
return filename, err
}
func LoadJsonnetfile(filepath string) (spec.JsonnetFile, error) {
m := spec.JsonnetFile{} m := spec.JsonnetFile{}
f, err := os.Open(filename) if _, err := os.Stat(filepath); err != nil {
return m, err
}
f, err := os.Open(filepath)
if err != nil { if err != nil {
return m, err return m, err
} }

35
pkg/packages_test.go Normal file
View file

@ -0,0 +1,35 @@
// Copyright 2018 jsonnet-bundler 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 pkg
import (
"testing"
"github.com/jsonnet-bundler/jsonnet-bundler/spec"
)
func TestInsert(t *testing.T) {
deps := []*spec.Dependency{&spec.Dependency{Name: "test1", Version: "latest"}}
dep := &spec.Dependency{Name: "test2", Version: "latest"}
res, err := insertDependency(deps, dep)
if err != nil {
t.Fatal(err)
}
if len(res) != 2 {
t.Fatal("Incorrectly inserted")
}
}

View file

@ -31,4 +31,5 @@ type Dependency struct {
Name string `json:"name"` Name string `json:"name"`
Source Source `json:"source"` Source Source `json:"source"`
Version string `json:"version"` Version string `json:"version"`
DepSource string `json:"-"`
} }