├── retrodep ├── testdata │ ├── gosource │ │ ├── ignored.go │ │ └── vendor │ │ │ └── github.com │ │ │ ├── eggs │ │ │ └── ham │ │ │ │ ├── ham.go │ │ │ │ └── spam │ │ │ │ └── ignored.go │ │ │ └── foo │ │ │ └── bar │ │ │ └── bar.go │ ├── glide │ │ ├── main.go │ │ ├── vendor │ │ │ └── github.com │ │ │ │ ├── pborman │ │ │ │ └── uuid │ │ │ │ │ └── test.go │ │ │ │ └── spf13 │ │ │ │ └── pflag │ │ │ │ └── test.go │ │ ├── glide.yaml │ │ └── glide.lock │ ├── godep │ │ ├── nonl.txt │ │ ├── importcomment.go │ │ ├── nl.go │ │ ├── nonl.go │ │ └── Godeps │ │ │ └── Godeps.json │ ├── multi │ │ ├── abc │ │ │ ├── abc.go │ │ │ └── vendor │ │ │ │ └── ghi │ │ │ │ └── ghi.go │ │ └── def │ │ │ ├── def.go │ │ │ └── vendor │ │ │ └── ghi │ │ │ └── ghi.go │ ├── importcommentsub │ │ ├── main.go │ │ └── sub │ │ │ └── main.go │ └── importcomment │ │ └── main.go ├── vcsnames.go ├── glide │ ├── glide_test.go │ └── glide.go ├── errors.go ├── doc.go ├── exec_test.go ├── vendored_test.go ├── filehash_test.go ├── hg.go ├── filehash.go ├── git.go ├── workingtree_test.go ├── hg_test.go ├── git_test.go ├── gosource_test.go ├── workingtree.go ├── vendored.go └── gosource.go ├── .gitignore ├── .travis.yml ├── go.mod ├── Makefile ├── go.sum ├── extras └── retrodiff ├── main_test.go ├── README.md ├── main.go └── LICENSE /retrodep/testdata/gosource/ignored.go: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /retrodep/testdata/glide/main.go: -------------------------------------------------------------------------------- 1 | package glide 2 | -------------------------------------------------------------------------------- /retrodep/testdata/godep/nonl.txt: -------------------------------------------------------------------------------- 1 | No newline at the end -------------------------------------------------------------------------------- /retrodep/testdata/multi/abc/abc.go: -------------------------------------------------------------------------------- 1 | package abc 2 | -------------------------------------------------------------------------------- /retrodep/testdata/multi/def/def.go: -------------------------------------------------------------------------------- 1 | package def 2 | -------------------------------------------------------------------------------- /retrodep/testdata/gosource/vendor/github.com/eggs/ham/ham.go: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /retrodep/testdata/gosource/vendor/github.com/foo/bar/bar.go: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /retrodep/testdata/multi/abc/vendor/ghi/ghi.go: -------------------------------------------------------------------------------- 1 | package ghi 2 | -------------------------------------------------------------------------------- /retrodep/testdata/multi/def/vendor/ghi/ghi.go: -------------------------------------------------------------------------------- 1 | package ghi 2 | -------------------------------------------------------------------------------- /retrodep/testdata/importcommentsub/main.go: -------------------------------------------------------------------------------- 1 | package importcomment 2 | -------------------------------------------------------------------------------- /retrodep/testdata/gosource/vendor/github.com/eggs/ham/spam/ignored.go: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /retrodep/testdata/godep/importcomment.go: -------------------------------------------------------------------------------- 1 | package foo // import "godep/foo" 2 | -------------------------------------------------------------------------------- /retrodep/testdata/glide/vendor/github.com/pborman/uuid/test.go: -------------------------------------------------------------------------------- 1 | package uuid 2 | -------------------------------------------------------------------------------- /retrodep/testdata/glide/vendor/github.com/spf13/pflag/test.go: -------------------------------------------------------------------------------- 1 | package pflag 2 | -------------------------------------------------------------------------------- /retrodep/testdata/godep/nl.go: -------------------------------------------------------------------------------- 1 | package foo 2 | 3 | // No newline at the end of this line 4 | -------------------------------------------------------------------------------- /retrodep/testdata/godep/nonl.go: -------------------------------------------------------------------------------- 1 | package foo 2 | 3 | // No newline at the end of this line -------------------------------------------------------------------------------- /retrodep/testdata/importcomment/main.go: -------------------------------------------------------------------------------- 1 | package importcomment // import "importcomment" 2 | -------------------------------------------------------------------------------- /retrodep/testdata/importcommentsub/sub/main.go: -------------------------------------------------------------------------------- 1 | package sub // import "importcomment/sub" 2 | -------------------------------------------------------------------------------- /retrodep/testdata/glide/glide.yaml: -------------------------------------------------------------------------------- 1 | package: github.com/release-engineering/retrodep/testdata/glide 2 | -------------------------------------------------------------------------------- /retrodep/testdata/godep/Godeps/Godeps.json: -------------------------------------------------------------------------------- 1 | { 2 | "ImportPath": "example.com/godep" 3 | } 4 | -------------------------------------------------------------------------------- /retrodep/testdata/glide/glide.lock: -------------------------------------------------------------------------------- 1 | imports: 2 | - name: github.com/pborman/uuid 3 | version: ca53cad383cad2479bbba7f7a1a05797ec1386e4 4 | - name: github.com/spf13/pflag 5 | version: 583c0c0531f06d5278b7d917446061adc344b5cd 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | branches: 3 | only: 4 | - master 5 | - v0 6 | sudo: false 7 | before_install: 8 | - make tools 9 | - go get -t ./... 10 | script: 11 | - make check 12 | - make test 13 | - make build 14 | after_success: 15 | - make coveralls 16 | notifications: 17 | email: false 18 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/release-engineering/retrodep/v2 2 | 3 | require ( 4 | github.com/Masterminds/semver v1.4.2 5 | github.com/kr/pretty v0.1.0 // indirect 6 | github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 7 | github.com/pkg/errors v0.8.1 8 | golang.org/x/tools v0.0.0-20190325161752-5a8dccf5b48a 9 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect 10 | gopkg.in/yaml.v2 v2.2.2 11 | ) 12 | -------------------------------------------------------------------------------- /retrodep/vcsnames.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | const vcsGit = "git" 19 | const vcsHg = "hg" 20 | -------------------------------------------------------------------------------- /retrodep/glide/glide_test.go: -------------------------------------------------------------------------------- 1 | package glide 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestGlideFalse(t *testing.T) { 8 | glide, err := LoadGlide("../testdata/glide/") 9 | if err != nil { 10 | t.Fatal("failed to load the lock file", err) 11 | } 12 | if glide.Imports[0].Name != "github.com/pborman/uuid" { 13 | t.Fatalf("expected '%v', got '%v'", "github.com/pborman/uuid", glide.Imports[0].Name) 14 | } 15 | if glide.Imports[0].Version != "ca53cad383cad2479bbba7f7a1a05797ec1386e4" { 16 | t.Fatalf("expected '%v', got '%v'", "ca53cad383cad2479bbba7f7a1a05797ec1386e4", glide.Imports[0].Version) 17 | } 18 | if len(glide.Imports) != 2 { 19 | t.Fatalf("expected '%v', got '%v'", 2, len(glide.Imports)) 20 | } 21 | if glide.Package != "github.com/release-engineering/retrodep/testdata/glide" { 22 | t.Fatalf("expected '%v', got '%v'", "github.com/release-engineering/retrodep/testdata/glide", glide.Package) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /retrodep/errors.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import "errors" 19 | 20 | // ErrorNoGo indicates there is no Go source code to process. 21 | var ErrorNoGo = errors.New("no Go source code to process") 22 | 23 | // ErrorNeedImportPath indicates the import path for the project 24 | // cannot be determined automatically and must be provided. 25 | var ErrorNeedImportPath = errors.New("unable to determine import path") 26 | 27 | // ErrorVersionNotFound indicates a vendored project does not match any semantic 28 | // tag in the upstream revision control system. 29 | var ErrorVersionNotFound = errors.New("version not found") 30 | 31 | // ErrorUnknownVCS indicates the upstream version control system is not one of 32 | // those for which support is implemented in retrodep. 33 | var ErrorUnknownVCS = errors.New("unknown VCS") 34 | 35 | // ErrorNoFiles indicates there are no files to compare hashes of 36 | var ErrorNoFiles = errors.New("no files to hash") 37 | 38 | // ErrorInvalidRef indicates the ref is not a tag or a revision 39 | // (perhaps it is a branch name instead). 40 | var ErrorInvalidRef = errors.New("invalid ref") 41 | -------------------------------------------------------------------------------- /retrodep/glide/glide.go: -------------------------------------------------------------------------------- 1 | package glide 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | 7 | "gopkg.in/yaml.v2" 8 | ) 9 | 10 | type glideLock struct { 11 | Imports []Import `json:"imports"` 12 | } 13 | 14 | type glideConf struct { 15 | Package string `json:"package"` 16 | Import []struct { 17 | Package string 18 | Repo string `json:"omitempty"` 19 | } 20 | } 21 | 22 | // Import represents an imported package. 23 | type Import struct { 24 | Name string `json:"name"` 25 | Version string `json:"version"` 26 | Repo string `json:"repo"` 27 | } 28 | 29 | // Glide represents the glide configuration. 30 | type Glide struct { 31 | Package string 32 | Imports []Import 33 | } 34 | 35 | // LoadGlide tries to load glide.lock and glide.yaml and extract 36 | // import information. In case no glide.lock is present, it will use 37 | // the import information from glide.yaml. 38 | func LoadGlide(projectRoot string) (*Glide, error) { 39 | lockImports := []Import{} 40 | lockFile, err := os.Open(filepath.Join(projectRoot, "glide.lock")) 41 | if err == nil { 42 | defer lockFile.Close() 43 | lock := glideLock{} 44 | if err != nil { 45 | return nil, err 46 | } 47 | err = yaml.NewDecoder(lockFile).Decode(&lock) 48 | if err != nil { 49 | return nil, err 50 | } 51 | lockImports = lock.Imports 52 | } else if !os.IsNotExist(err) { 53 | return nil, err 54 | } 55 | 56 | confFile, err := os.Open(filepath.Join(projectRoot, "glide.yaml")) 57 | if err != nil { 58 | return nil, err 59 | } 60 | defer confFile.Close() 61 | conf := glideConf{} 62 | err = yaml.NewDecoder(confFile).Decode(&conf) 63 | if err != nil { 64 | return nil, err 65 | } 66 | 67 | if len(lockImports) == 0 { 68 | for _, imp := range conf.Import { 69 | lockImports = append(lockImports, Import{Name: imp.Package, Repo: imp.Repo}) 70 | } 71 | } 72 | 73 | return &Glide{Imports: lockImports, Package: conf.Package}, nil 74 | } 75 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | BIN_DIR = bin 2 | BIN_NAME = retrodep 3 | BIN = $(BIN_DIR)/$(BIN_NAME) 4 | PREFIX = /usr/local/bin 5 | TOOLS = golang.org/x/tools/cmd/goimports golang.org/x/lint/golint github.com/mattn/goveralls 6 | COVERPROFILE = profile.cov 7 | 8 | GOBIN = $$GOPATH/bin 9 | GOVERALLS = $(GOBIN)/goveralls 10 | GOIMPORTS = $(GOBIN)/goimports 11 | GOFMT = gofmt 12 | GOLINT = $(GOBIN)/golint 13 | 14 | DEFAULT_BRANCH = master 15 | FILES_TO_CHECK = $(shell git diff --no-renames --name-status $(DEFAULT_BRANCH) -- | grep '\.go$$' | grep -v D | cut -f 2) 16 | 17 | .PHONY: all clean deps test build fmt lint install check coveralls 18 | 19 | all: build 20 | 21 | clean: 22 | @echo '\033[0;31mRemoving generated binaries\033[0m'; \ 23 | rm -rf $(BIN_DIR) 24 | 25 | build: 26 | @echo '\033[0;32mBuilding\033[0m'; \ 27 | go build -o $(BIN) ./main.go 28 | 29 | install: 30 | @echo 'Installing retrodep to \033[0;32m$(PREFIX)/$(BIN_NAME)\033[0m'; \ 31 | install $(BIN) $(PREFIX)/$(BIN_NAME) 32 | 33 | tools: 34 | @echo 'Installing \033[0;32m$(TOOLS)\033[0m'; \ 35 | for tool in $(TOOLS); do \ 36 | go get -u $$tool; \ 37 | done 38 | 39 | test: 40 | @echo 'Running \033[0;32mtests\033[0m'; \ 41 | go test . -v; \ 42 | go test ./retrodep/glide -v; \ 43 | go test ./retrodep -v -covermode=count -coverprofile=$(COVERPROFILE) 44 | 45 | fmt: 46 | @if test -n "$(FILES_TO_CHECK)"; then \ 47 | echo 'Running \033[0;32mgofmt\033[0m'; \ 48 | out=$$($(GOFMT) -l $(FILES_TO_CHECK)); \ 49 | echo $$out; \ 50 | test -z "$$out"; \ 51 | fi 52 | 53 | lint: 54 | @if test -n "$(FILES_TO_CHECK)"; then \ 55 | echo 'Running \033[0;32mgolint\033[0m'; \ 56 | out=$$($(GOLINT) $(FILES_TO_CHECK)); \ 57 | echo $$out; \ 58 | test -z "$$out"; \ 59 | fi 60 | 61 | imports: 62 | @if test -n "$(FILES_TO_CHECK)"; then \ 63 | echo 'Running \033[0;32mgoimports\033[0m'; \ 64 | out=$$($(GOIMPORTS) -l $(FILES_TO_CHECK)); \ 65 | echo $$out; \ 66 | test -z "$$out"; \ 67 | fi 68 | 69 | check: fmt imports lint 70 | 71 | coveralls: 72 | @echo '\033[0;32mPublishing coverage\033[0m'; \ 73 | $(GOVERALLS) -coverprofile=$(COVERPROFILE) -service=travis-ci 74 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/Masterminds/semver v1.4.2 h1:WBLTQ37jOCzSLtXNdoo8bNM8876KhNqOKvrlGITgsTc= 2 | github.com/Masterminds/semver v1.4.2/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= 3 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= 4 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 5 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 6 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 7 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 8 | github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 h1:lDH9UUVJtmYCjyT0CI4q8xvlXPxeZ0gYCVvWbmPlp88= 9 | github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= 10 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 11 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 12 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 13 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 14 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 15 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 16 | golang.org/x/tools v0.0.0-20190325161752-5a8dccf5b48a h1:iEgSlyueP+hVXFS7PZk7z5e23iHin+tpXArziYTt574= 17 | golang.org/x/tools v0.0.0-20190325161752-5a8dccf5b48a/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 18 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 19 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 20 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= 21 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 22 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 23 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 24 | -------------------------------------------------------------------------------- /retrodep/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | // Package retrodep provides a way to represent Go source code in a 17 | // filesystem, and taken from a source code repository. It allows 18 | // mapping vendored packages back to the original versions they came 19 | // from. 20 | // 21 | // A GoSource represents a filesystem tree containing Go source 22 | // code. Create it using NewGoSource or FindGoSources. The Project and 23 | // VendoredProjects methods return information about the top-level 24 | // project and the vendored projects it has. 25 | // 26 | // src := retrodep.NewGoSource(path, nil) 27 | // proj, perr := src.Project(importPath) 28 | // vendored, verr := src.VendoredProjects() 29 | // 30 | // Both of these methods use RepoPath to describe the projects. If a 31 | // glide configuration file is found, Version will be filled in for 32 | // each vendored dependency. 33 | // 34 | // The FindGoSources function looks for Go source code in the provided 35 | // path. If it is not found there, the immediate subdirectories are 36 | // searched. This function allows for repositories which are 37 | // collections of independently-vendored projects. 38 | // 39 | // The NewWorkingTree function makes a temporary local copy of the 40 | // upstream repository. 41 | // 42 | // wt, err := retrodep.NewWorkingTree(&proj.RepoRoot) 43 | // 44 | // The DescribeProject function takes a RepoPath, a WorkingTree, and 45 | // path within the tree, and returns a Representation, indicating the 46 | // upstream version of the project or vendored project, e.g. 47 | // 48 | // ref, rerr := retrodep.DescribeProject(proj, wt, src.Path) 49 | // 50 | // It does this by comparing file hashes of the local files with those 51 | // from commits in the upstream repository. 52 | package retrodep 53 | -------------------------------------------------------------------------------- /retrodep/exec_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "fmt" 20 | "os" 21 | "os/exec" 22 | "strconv" 23 | "testing" 24 | ) 25 | 26 | const ( 27 | envHelper = "GO_WANT_HELPER_PROCESS" 28 | envStdout = "STDOUT" 29 | envStderr = "STDERR" 30 | envExitStatus = "EXIT_STATUS" 31 | ) 32 | 33 | var mockedExitStatus int 34 | var mockedStdout, mockedStderr string 35 | 36 | // Capture exec.Command calls via execCommand and make them run our 37 | // fake version instead. This returns a function which the caller 38 | // should defer a call to in order to reset execCommand. 39 | func mockExecCommand() func() { 40 | execCommand = fakeExecCommand 41 | 42 | // Reset it afterwards 43 | return func() { 44 | execCommand = exec.Command 45 | mockedExitStatus = 0 46 | mockedStdout = "" 47 | mockedStderr = "" 48 | } 49 | } 50 | 51 | // Run this test binary (again!) but transfer control immediately to 52 | // TestHelper, telling it how to act. 53 | func fakeExecCommand(command string, args ...string) *exec.Cmd { 54 | testBinary := os.Args[0] 55 | opts := []string{"-test.run=TestHelper", "--", command} 56 | opts = append(opts, args...) 57 | cmd := exec.Command(testBinary, opts...) 58 | cmd.Env = []string{ 59 | envHelper + "=1", 60 | envStdout + "=" + mockedStdout, 61 | envStderr + "=" + mockedStderr, 62 | envExitStatus + "=" + strconv.Itoa(mockedExitStatus), 63 | } 64 | return cmd 65 | } 66 | 67 | // This runs in its own process (see fakeExecCommand) and mocks the 68 | // command being run. 69 | func TestHelper(t *testing.T) { 70 | if os.Getenv(envHelper) != "1" { 71 | return 72 | } 73 | fmt.Print(os.Getenv(envStdout)) 74 | fmt.Fprint(os.Stderr, os.Getenv(envStderr)) 75 | exit, _ := strconv.Atoi(os.Getenv(envExitStatus)) 76 | os.Exit(exit) 77 | } 78 | -------------------------------------------------------------------------------- /extras/retrodiff: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright (C) 2019, 2020 Tim Waugh 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see . 17 | 18 | # This is a simple wrapper script to read container.yaml files 19 | # (http://osbs.readthedocs.io/) to find enough information to give to 20 | # retrodep in -diff mode. It also ignores files used for 'dist-git' 21 | # layouts. 22 | 23 | if [ $# -lt 1 ]; then 24 | echo >&2 "Supply VERSION, then optional retrodep flags" 25 | exit 1 26 | fi 27 | VERSION=$1 28 | shift 29 | 30 | # Find import path from container.yaml 31 | MODULES=$(python /dev/fd/3 3<<"EOF" . 15 | 16 | package main 17 | 18 | import ( 19 | "io" 20 | "io/ioutil" 21 | "os" 22 | "syscall" 23 | "testing" 24 | 25 | "github.com/release-engineering/retrodep/v2/retrodep" 26 | ) 27 | 28 | func captureStdout(t *testing.T) (r io.Reader, reset func()) { 29 | stdout := int(os.Stdout.Fd()) 30 | orig, err := syscall.Dup(stdout) 31 | if err != nil { 32 | t.Fatal(err) 33 | } 34 | r, w, err := os.Pipe() 35 | if err != nil { 36 | t.Fatal(err) 37 | } 38 | err = syscall.Dup2(int(w.Fd()), stdout) 39 | if err != nil { 40 | t.Fatal(err) 41 | } 42 | 43 | reset = func() { 44 | w.Close() 45 | err := syscall.Dup2(orig, stdout) 46 | if err != nil { 47 | t.Fatal(err) 48 | } 49 | } 50 | 51 | return 52 | } 53 | 54 | func TestDisplayUnknown(t *testing.T) { 55 | tcs := []struct { 56 | name string 57 | ref *retrodep.Reference 58 | templateArg string 59 | expected string 60 | }{ 61 | { 62 | "nil ref, empty templateArg", 63 | nil, 64 | "", 65 | "*example.com/foo ?\n", 66 | }, 67 | { 68 | "with ref, non-zero templateArg", 69 | &retrodep.Reference{Pkg: "example.com/foo"}, 70 | "filled templateArg", 71 | "*example.com/foo ?\n", 72 | }, 73 | } 74 | 75 | for _, tc := range tcs { 76 | tc := tc 77 | 78 | t.Run(tc.name, func(t *testing.T) { 79 | *templateArg = tc.templateArg 80 | r, reset := captureStdout(t) 81 | displayUnknown(nil, "*", tc.ref, "example.com/foo") 82 | reset() 83 | output, err := ioutil.ReadAll(r) 84 | if err != nil { 85 | t.Fatal(err) 86 | } 87 | if string(output) != tc.expected { 88 | t.Errorf("expected %v but got %v", 89 | tc.expected, string(output)) 90 | } 91 | }) 92 | } 93 | } 94 | 95 | func TestGetTemplate(t *testing.T) { 96 | tcs := []struct { 97 | name string 98 | args []string 99 | expected string 100 | }{ 101 | { 102 | "default", 103 | []string{"retrodep", "."}, 104 | defaultTemplate, 105 | }, 106 | { 107 | "go-template", 108 | []string{"retrodep", "-o", "go-template={{.Pkg}}", "."}, 109 | "{{.Pkg}}", 110 | }, 111 | { 112 | "compatibility", 113 | []string{"retrodep", "-template", "@{{.Rev}}", "."}, 114 | "{{.Pkg}}@{{.Rev}}", 115 | }, 116 | } 117 | 118 | for _, tc := range tcs { 119 | tc := tc 120 | 121 | // Reset the flags. 122 | *templateArg = "" 123 | *outputArg = "" 124 | 125 | t.Run(tc.name, func(t *testing.T) { 126 | processArgs(tc.args) 127 | tmpl := getTemplate() 128 | if tmpl != tc.expected { 129 | t.Errorf("expected %v but got %v", 130 | tc.expected, tmpl) 131 | } 132 | }) 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /retrodep/vendored_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "testing" 20 | ) 21 | 22 | func TestVendoredProjects(t *testing.T) { 23 | src, err := NewGoSource("testdata/gosource", nil) 24 | if err != nil { 25 | t.Fatal(err) 26 | } 27 | expected := []string{ 28 | "github.com/eggs/ham", 29 | "github.com/foo/bar", 30 | } 31 | got, err := src.VendoredProjects() 32 | if err != nil { 33 | t.Fatal(err) 34 | } 35 | matched := len(got) == len(expected) 36 | if !matched { 37 | t.Errorf("%d != %d", len(got), len(expected)) 38 | } 39 | if matched { 40 | for _, repo := range expected { 41 | if _, ok := got[repo]; !ok { 42 | t.Errorf("%s not returned", repo) 43 | matched = false 44 | break 45 | } 46 | } 47 | } 48 | if !matched { 49 | t.Errorf("%v != %v", got, expected) 50 | } 51 | } 52 | 53 | func TestChooseBestTag(t *testing.T) { 54 | tags := []string{ 55 | "1.2.3-beta1", 56 | "1.2.2", 57 | "1.2.2-beta2", 58 | } 59 | best := chooseBestTag(tags) 60 | if best != "1.2.2" { 61 | t.Errorf("wrong best tag (%s)", best) 62 | } 63 | } 64 | 65 | type dummyHasher struct{} 66 | 67 | func (h *dummyHasher) Hash(abs, rel string) (FileHash, error) { 68 | return "foo", nil 69 | } 70 | 71 | type mockVendorWorkingTree struct { 72 | stubWorkingTree 73 | 74 | localHashes FileHashes 75 | } 76 | 77 | const matchVersion = "v1.0.0" 78 | const matchRevision = "0123456789abcdef" 79 | 80 | func (wt *mockVendorWorkingTree) FileHashesFromRef(ref, _ string) (FileHashes, error) { 81 | if ref == matchRevision || ref == matchVersion { 82 | // Pretend v1.0.0 is an exact copy of the local files. 83 | return wt.localHashes, nil 84 | } 85 | 86 | // Pretend all other refs have no content at all. 87 | return make(FileHashes), nil 88 | } 89 | 90 | func (wt *mockVendorWorkingTree) RevisionFromTag(tag string) (string, error) { 91 | if tag != matchVersion { 92 | return "", ErrorVersionNotFound 93 | } 94 | return matchRevision, nil 95 | } 96 | 97 | func (wt *mockVendorWorkingTree) ReachableTag(rev string) (tag string, err error) { 98 | if rev == matchVersion { 99 | tag = rev 100 | } else { 101 | err = ErrorVersionNotFound 102 | } 103 | return 104 | } 105 | 106 | func (wt *mockVendorWorkingTree) VersionTags() ([]string, error) { 107 | return []string{"v2.0.0", "v1.0.0"}, nil 108 | } 109 | 110 | func TestDescribeProject(t *testing.T) { 111 | src, err := NewGoSource("testdata/gosource", nil) 112 | if err != nil { 113 | t.Fatal(err) 114 | } 115 | 116 | proj, err := src.Project("github.com/foo/bar") 117 | if err != nil { 118 | t.Fatal(err) 119 | } 120 | 121 | wt := &mockVendorWorkingTree{} 122 | wt.hasher = &dummyHasher{} 123 | 124 | // Make a copy of the local file hashes, so we can mock them 125 | // for "v1.0.0" in the working tree. 126 | wt.localHashes, err = src.hashLocalFiles(wt, proj, src.Path) 127 | if err != nil { 128 | t.Fatal(err) 129 | } 130 | 131 | ref, err := src.DescribeProject(proj, wt, src.Path, nil) 132 | if err != nil { 133 | t.Fatal(err) 134 | } 135 | 136 | if ref.Ver != matchVersion { 137 | t.Errorf("Version: got %s but expected %s", ref.Ver, matchVersion) 138 | } 139 | if ref.Rev != matchRevision { 140 | t.Errorf("Revision: got %s but expected %s", ref.Rev, matchRevision) 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /retrodep/filehash_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "sort" 20 | "testing" 21 | ) 22 | 23 | func TestSha256Hasher(t *testing.T) { 24 | h := sha256Hasher{} 25 | // from sha256sum: 26 | emptysum := FileHash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") 27 | fh, err := h.Hash("", "testdata/gosource/ignored.go") 28 | if err != nil { 29 | t.Fatal(err) 30 | } 31 | if fh != emptysum { 32 | t.Errorf("unexpected hash: got %s, want %s", fh, emptysum) 33 | } 34 | } 35 | 36 | func TestNewFileHashes(t *testing.T) { 37 | hashes, err := NewFileHashes(&gitHasher{}, "testdata/gosource", nil) 38 | if err != nil { 39 | t.Fatal(err) 40 | } 41 | if hashes == nil { 42 | t.Fatal("NewFileHashes returned nil map") 43 | } 44 | emptyhash := FileHash("e69de29bb2d1d6434b8b29ae775ad8c2e48c5391") 45 | expected := map[string]FileHash{ 46 | "ignored.go": emptyhash, 47 | "vendor/github.com/foo/bar/bar.go": emptyhash, 48 | "vendor/github.com/eggs/ham/ham.go": emptyhash, 49 | "vendor/github.com/eggs/ham/spam/ignored.go": emptyhash, 50 | } 51 | if len(hashes) != len(expected) { 52 | t.Fatalf("len(hashes[%v]) != %d", hashes, len(expected)) 53 | } 54 | for key, value := range expected { 55 | got, ok := hashes[key] 56 | if !ok { 57 | t.Errorf("%s missing", key) 58 | continue 59 | } 60 | if got != value { 61 | t.Errorf("%s: wrong hash (%s != %s)", key, got, value) 62 | } 63 | } 64 | } 65 | 66 | func TestNewFileHashesExclude(t *testing.T) { 67 | excludes := make(map[string]struct{}) 68 | excludes["testdata/gosource/ignored.go"] = struct{}{} 69 | hashes, err := NewFileHashes(&gitHasher{}, "testdata/gosource", excludes) 70 | if err != nil { 71 | t.Fatal(err) 72 | } 73 | emptyhash := FileHash("e69de29bb2d1d6434b8b29ae775ad8c2e48c5391") 74 | expected := map[string]FileHash{ 75 | "vendor/github.com/foo/bar/bar.go": emptyhash, 76 | "vendor/github.com/eggs/ham/ham.go": emptyhash, 77 | "vendor/github.com/eggs/ham/spam/ignored.go": emptyhash, 78 | } 79 | if len(hashes) != len(expected) { 80 | t.Fatalf("len(hashes[%v]) != %d", hashes, len(expected)) 81 | } 82 | for key, value := range expected { 83 | got, ok := hashes[key] 84 | if !ok { 85 | t.Errorf("%s missing", key) 86 | continue 87 | } 88 | if got != value { 89 | t.Errorf("%s: wrong hash (%s != %s)", key, got, value) 90 | } 91 | } 92 | } 93 | 94 | func TestIsSubsetOf(t *testing.T) { 95 | hasher := &gitHasher{} 96 | hashes, err := NewFileHashes(hasher, "testdata/gosource", nil) 97 | if err != nil { 98 | t.Fatal(err) 99 | } 100 | 101 | if !hashes.IsSubsetOf(hashes) { 102 | t.Fatalf("not subset of self") 103 | } 104 | 105 | other := make(FileHashes) 106 | for k, v := range hashes { 107 | other[k] = v 108 | } 109 | hashes["foo"] = FileHash("") 110 | if hashes.IsSubsetOf(other) { 111 | t.Fail() 112 | } 113 | } 114 | 115 | func TestMismatches(t *testing.T) { 116 | hasher := &gitHasher{} 117 | hashes, err := NewFileHashes(hasher, "testdata/gosource", nil) 118 | if err != nil { 119 | t.Fatal(err) 120 | } 121 | 122 | if hashes.Mismatches(hashes, false) != nil { 123 | t.Fatalf("mismatches self") 124 | } 125 | 126 | other := make(FileHashes) 127 | for k, v := range hashes { 128 | other[k] = v 129 | } 130 | 131 | other["foo"] = FileHash("") 132 | if hashes.Mismatches(hashes, false) != nil { 133 | t.Fatalf("extra value in s reported as mismatch") 134 | } 135 | 136 | eq := func(a sort.StringSlice, b sort.StringSlice) bool { 137 | if len(a) != len(b) { 138 | return false 139 | } 140 | a.Sort() 141 | b.Sort() 142 | for i, v := range a { 143 | if b[i] != v { 144 | return false 145 | } 146 | } 147 | return true 148 | } 149 | 150 | hashes["foo"] = FileHash("123") 151 | hashes["bar"] = FileHash("123") 152 | mismatches := hashes.Mismatches(other, false) 153 | if !eq(mismatches, []string{"foo", "bar"}) { 154 | t.Errorf("got %v, expected {\"foo\", \"bar\"}", mismatches) 155 | } 156 | 157 | mismatches = hashes.Mismatches(other, true) 158 | if len(mismatches) != 1 { 159 | t.Errorf("too many mismatches returned: %v", mismatches) 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /retrodep/hg.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "encoding/xml" 20 | "fmt" 21 | "io/ioutil" 22 | "os" 23 | "path/filepath" 24 | "strings" 25 | "time" 26 | 27 | "github.com/Masterminds/semver" 28 | "github.com/pkg/errors" 29 | ) 30 | 31 | // This file contains methods specific to working with hg. 32 | 33 | type hgWorkingTree struct { 34 | anyWorkingTree 35 | } 36 | 37 | type hgLogEntry struct { 38 | Node string `xml:"node,attr"` 39 | Date []byte `xml:"date"` 40 | Tag string `xml:"tag"` 41 | } 42 | type hgLogs struct { 43 | XMLName xml.Name `xml:"log"` 44 | LogEntries []hgLogEntry `xml:"logentry"` 45 | } 46 | 47 | /// log runs 'hg log --template xml', with the additional args if args 48 | /// is not nil, and returns the log entries. If expect is not 0, an 49 | /// error is returned if the number of log entries is different. 50 | func (h *hgWorkingTree) log(args []string, expect int) ([]hgLogEntry, error) { 51 | logArgs := []string{"log", "--encoding", "utf-8", "--template", "xml"} 52 | if args != nil { 53 | logArgs = append(logArgs, args...) 54 | } 55 | stdout, stderr, err := h.run(logArgs...) 56 | if err != nil { 57 | h.showOutput(stdout, stderr) 58 | return nil, err 59 | } 60 | var logs hgLogs 61 | err = xml.Unmarshal(stdout.Bytes(), &logs) 62 | if err != nil { 63 | return nil, err 64 | } 65 | entries := logs.LogEntries 66 | if expect != 0 && len(entries) != expect { 67 | return nil, fmt.Errorf( 68 | "unexpected log output: %s: %d logentry elements (expected %d)", 69 | strings.Join(logArgs, " "), len(entries), expect) 70 | } 71 | return entries, nil 72 | } 73 | 74 | // Revisions returns all revisions in the hg repository, using 'hg log'. 75 | func (h *hgWorkingTree) Revisions() ([]string, error) { 76 | entries, err := h.log(nil, 0) 77 | if err != nil { 78 | return nil, err 79 | } 80 | revisions := make([]string, 0) 81 | for _, entry := range entries { 82 | revisions = append(revisions, entry.Node) 83 | } 84 | return revisions, nil 85 | } 86 | 87 | // RevisionFromTag returns the revision for the given tag, using 'hg 88 | // log -r "tag(...)"'. 89 | func (h *hgWorkingTree) RevisionFromTag(tag string) (string, error) { 90 | entries, err := h.log([]string{"-r", "tag(" + tag + ")"}, 1) 91 | if err != nil { 92 | return "", err 93 | } 94 | return entries[0].Node, nil 95 | } 96 | 97 | // RevSync updates the working tree to reflect the revision rev, using 98 | // 'hg update -r ...'. The working tree must not have been locally 99 | // modified. 100 | func (h *hgWorkingTree) RevSync(rev string) error { 101 | return h.anyWorkingTree.TagSync(rev) 102 | } 103 | 104 | // TimeFromRevision returns the commit timestamp for the revision 105 | // rev, using 'hg log -r ...'. 106 | func (h *hgWorkingTree) TimeFromRevision(rev string) (time.Time, error) { 107 | var t time.Time 108 | entries, err := h.log([]string{"-r", rev}, 1) 109 | if err != nil { 110 | return t, err 111 | } 112 | err = t.UnmarshalText(entries[0].Date) 113 | return t, err 114 | } 115 | 116 | // ReachableTag returns the most recent reachable semver tag, using hg 117 | // log -r "ancestors(...) & tag(r're:...')". It fails with 118 | // ErrorVersionNotFound if no suitable tag is found. 119 | func (h *hgWorkingTree) ReachableTag(rev string) (string, error) { 120 | // Find up to 10 reachable tags from the revision that might be semver tags 121 | revset := "ancestors(" + rev + ") & tag(r're:v?[0-9]')" 122 | entries, err := h.log([]string{"-r", revset, "--limit", "10"}, 0) 123 | if err != nil { 124 | return "", err 125 | } 126 | 127 | if len(entries) == 0 { 128 | return "", ErrorVersionNotFound 129 | } 130 | 131 | // If any is a semver tag, use that 132 | for _, entry := range entries { 133 | _, err := semver.NewVersion(entry.Tag) 134 | if err == nil { 135 | return entry.Tag, nil 136 | } 137 | } 138 | 139 | // Otherwise just take the first one 140 | return entries[0].Tag, nil 141 | } 142 | 143 | // FileHashesFromRef returns the file hashes for the given tag or 144 | // revision ref. 145 | func (h *hgWorkingTree) FileHashesFromRef(ref, subPath string) (FileHashes, error) { 146 | dir, err := ioutil.TempDir("", "retrodep.") 147 | if err != nil { 148 | return nil, errors.Wrapf(err, "FileHashesFromRef(%s)", ref) 149 | } 150 | defer os.RemoveAll(dir) 151 | 152 | args := []string{"archive", "-r", ref, "--type", "files"} 153 | if subPath != "" { 154 | args = append(args, "--prefix", subPath) 155 | } 156 | args = append(args, dir) 157 | stdout, stderr, err := h.run(args...) 158 | if err != nil { 159 | h.showOutput(stdout, stderr) 160 | return nil, err 161 | } 162 | return NewFileHashes(&sha256Hasher{}, filepath.Join(dir, subPath), nil) 163 | } 164 | -------------------------------------------------------------------------------- /retrodep/filehash.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "bufio" 20 | "crypto/sha256" 21 | "encoding/hex" 22 | "io" 23 | "os" 24 | "path" 25 | "path/filepath" 26 | "strings" 27 | 28 | "github.com/pkg/errors" 29 | ) 30 | 31 | // FileHash records the hash of a file in the format preferred by the 32 | // version control system that tracks it. 33 | type FileHash string 34 | 35 | // Hasher is the interface that wraps the Hash method. 36 | type Hasher interface { 37 | // Hash returns the file hash for the filename absPath, hashed 38 | // as though it were in the repository as filename 39 | // relativePath. 40 | Hash(relativePath, absPath string) (FileHash, error) 41 | } 42 | 43 | type sha256Hasher struct{} 44 | 45 | // Hash implements the Hasher interface generically using sha256. 46 | func (h sha256Hasher) Hash(relativePath, absPath string) (FileHash, error) { 47 | f, err := os.Open(absPath) 48 | if err != nil { 49 | return FileHash(""), errors.Wrapf(err, "hashing %s", absPath) 50 | } 51 | defer f.Close() 52 | 53 | hash := sha256.New() 54 | _, err = io.Copy(hash, f) 55 | if err != nil { 56 | return FileHash(""), errors.Wrapf(err, "hashing %s", absPath) 57 | } 58 | 59 | return FileHash(hex.EncodeToString(hash.Sum(nil))), nil 60 | } 61 | 62 | // FileHashes is a map of paths, relative to the top-level of the 63 | // version control system, to their hashes. 64 | type FileHashes map[string]FileHash 65 | 66 | // NewFileHashes returns a new FileHashes from a filesystem tree at root, 67 | // whose files belong to the version control system named in vcsCmd. Keys in 68 | // the excludes map are filenames to ignore. 69 | func NewFileHashes(h Hasher, root string, excludes map[string]struct{}) (FileHashes, error) { 70 | hashes := make(FileHashes) 71 | root = path.Clean(root) 72 | 73 | // Make a local copy of excludes we can safely modify 74 | excl := make(map[string]struct{}) 75 | if excludes != nil { 76 | for k, v := range excludes { 77 | excl[k] = v 78 | } 79 | } 80 | 81 | walkfn := func(path string, info os.FileInfo, err error) error { 82 | if err != nil { 83 | return err 84 | } 85 | if _, skip := excl[path]; skip { 86 | // This pathname has been ignored, either by caller 87 | // request or due to .gitattributes 88 | if info.IsDir() { 89 | return filepath.SkipDir 90 | } 91 | return nil 92 | } 93 | if info.IsDir() { 94 | // Check for .gitattributes in this directory 95 | // FIXME: gitattributes(5) describes a more complex file 96 | // format than handled here. Can git-check-attr(1) help? 97 | ga, err := os.Open(filepath.Join(path, ".gitattributes")) 98 | if err != nil { 99 | if os.IsNotExist(err) { 100 | err = nil 101 | } 102 | return err 103 | } 104 | defer ga.Close() 105 | 106 | scanner := bufio.NewScanner(bufio.NewReader(ga)) 107 | for scanner.Scan() { 108 | fields := strings.Fields(scanner.Text()) 109 | if len(fields) < 2 { 110 | continue 111 | } 112 | for _, field := range fields[1:] { 113 | if field == "export-subst" { 114 | // Not expected to have matching hash 115 | fn := filepath.Join(path, fields[0]) 116 | excl[fn] = struct{}{} 117 | break 118 | } 119 | } 120 | } 121 | 122 | return nil 123 | } 124 | if !info.Mode().IsRegular() { 125 | return nil 126 | } 127 | relativePath, err := filepath.Rel(root, path) 128 | if err != nil { 129 | return err 130 | } 131 | 132 | fileHash, err := h.Hash(relativePath, path) 133 | if err != nil { 134 | return err 135 | } 136 | hashes[relativePath] = fileHash 137 | return nil 138 | } 139 | err := filepath.Walk(root, walkfn) 140 | if err != nil { 141 | return nil, err 142 | } 143 | return hashes, nil 144 | } 145 | 146 | // IsSubsetOf returns true if these file hashes are a subset of s. 147 | func (h FileHashes) IsSubsetOf(s FileHashes) bool { 148 | return h.Mismatches(s, true) == nil 149 | } 150 | 151 | // Mismatches returns a slice of filenames from h whose hashes 152 | // mismatch those in s. If failFast is true at most one mismatch will 153 | // be returned. 154 | func (h FileHashes) Mismatches(s FileHashes, failFast bool) []string { 155 | var mismatches []string 156 | for path, fileHash := range h { 157 | sh, ok := s[path] 158 | if !ok { 159 | // File not present in s 160 | log.Debugf("%s: not present", path) 161 | mismatches = append(mismatches, path) 162 | } else if fileHash != sh { 163 | // Hash does not match 164 | log.Debugf("%s: hash mismatch", path) 165 | mismatches = append(mismatches, path) 166 | } 167 | 168 | if failFast && mismatches != nil { 169 | return mismatches 170 | } 171 | } 172 | 173 | return mismatches 174 | } 175 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Retrodep 2 | ======== 3 | 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/release-engineering/retrodep)](https://goreportcard.com/report/github.com/release-engineering/retrodep) 5 | [![GoDoc](https://godoc.org/github.com/release-engineering/retrodep?status.png)](https://godoc.org/github.com/release-engineering/retrodep) 6 | [![Build Status](https://travis-ci.org/release-engineering/retrodep.svg?branch=master)](https://travis-ci.org/release-engineering/retrodep) 7 | [![Coverage Status](https://coveralls.io/repos/github/release-engineering/retrodep/badge.svg)](https://coveralls.io/github/release-engineering/retrodep) 8 | 9 | This command inspects a Go source tree with vendored packages and attempts to work out the versions of the packages which are vendored, as well as the version of top-level package itself. 10 | 11 | It does this by comparing file hashes of the packages with those from the upstream repositories. 12 | 13 | If no semantic version tag matches but a commit is found that matches, a pseudo-version is generated. 14 | 15 | Installation 16 | ------------ 17 | 18 | ``` 19 | go get github.com/release-engineering/retrodep 20 | ``` 21 | 22 | Running 23 | ------- 24 | 25 | ``` 26 | retrodep: help requested 27 | usage: retrodep [OPTION]... PATH 28 | -debug 29 | show debugging output 30 | -deps 31 | show vendored dependencies (default true) 32 | -diff string 33 | compare with upstream ref (implies -deps=false) 34 | -exclude-from exclusions 35 | ignore directory entries matching globs in exclusions 36 | -help 37 | print help 38 | -importpath string 39 | top-level import path 40 | -o string 41 | output format, one of: go-template=... 42 | -only-importpath 43 | only show the top-level import path 44 | -template string 45 | go template to use for output with Reference fields (deprecated) 46 | -x exit on the first failure 47 | ``` 48 | 49 | In many cases retrodep can work out the import path for the top-level project. In those cases, simply supply the directory name to examine: 50 | ``` 51 | $ retrodep src 52 | ``` 53 | 54 | If it cannot determine the import path, provide it with -importpath: 55 | ``` 56 | $ retrodep -importpath github.com/example/name src 57 | ``` 58 | 59 | By default both the top-level project and its vendored dependencies are examined. To ignore vendored dependencies supply -deps=false: 60 | ``` 61 | $ retrodep -deps=false -importpath github.com/example/name src 62 | ``` 63 | 64 | If there are additional local files not expected to be part of the upstream version they can be excluded: 65 | ``` 66 | $ cat exclusions 67 | .git 68 | Dockerfile 69 | $ ls -d src/Dockerfile src/.git 70 | src/Dockerfile 71 | src/.git 72 | $ retrodep -exclude-from=exclusions src 73 | ``` 74 | 75 | Exit code 76 | --------- 77 | 78 | | Exit code | Reason | 79 | | ---------:|:------------------------------------------------ | 80 | | 0 | all versions were found (or -diff: no changes) | 81 | | 1 | any error was encountered other than those below | 82 | | 2 | a version was missing | 83 | | 3 | import path needed but not supplied | 84 | | 4 | no Go source code was found at the provided path | 85 | | 5 | in -diff mode, changes were found | 86 | 87 | Example output 88 | -------------- 89 | 90 | ``` 91 | $ retrodep $GOPATH/src/github.com/docker/distribution 92 | github.com/docker/distribution:v2.7.1 93 | github.com/docker/distribution:v2.7.1/github.com/Azure/azure-sdk-for-go:v16.2.1 94 | github.com/docker/distribution:v2.7.1/github.com/Azure/go-autorest:v10.8.1 95 | github.com/docker/distribution:v2.7.1/github.com/Shopify/logrus-bugsnag:v0.0.0-0.20171204154709-577dee27f20d 96 | github.com/docker/distribution:v2.7.1/github.com/aws/aws-sdk-go:v1.15.11 97 | github.com/docker/distribution:v2.7.1/github.com/beorn7/perks:v0.0.0-0.20160804124726-4c0e84591b9a 98 | github.com/docker/distribution:v2.7.1/github.com/bshuster-repo/logrus-logstash-hook:0.4 99 | github.com/docker/distribution:v2.7.1/github.com/bugsnag/bugsnag-go:v1.0.3-0.20150204195350-f36a9b3a9e01 100 | ... 101 | ``` 102 | 103 | In this example, 104 | 105 | * github.com/docker/distribution is the top-level package, and the upstream semantic version tag v2.7.1 matches 106 | * github.com/Azure/azure-sdk-for-go etc are vendored dependencies of distribution 107 | * github.com/Azure/azure-sdk-for-go, github.com/Azure/go-autorest, github.com/aws/awk-sdk-go, and github.com/bshuster-repo/logrus-logstash-hook all had matches with upstream semantic version tags 108 | * github.com/bugsnag/bugsnag-go matched a commit from which tag v1.0.2 was reachable (note: v1.0.2, not v1.0.3 -- see below) 109 | * github.com/beorn7/perks matched a commit from which there were no reachable semantic version tags 110 | 111 | Pseudo-versions 112 | --------------- 113 | 114 | The pseudo-versions generated by this tool are: 115 | 116 | * v0.0.0-0.yyyyddmmhhmmss-abcdefabcdef (commit with no relative tag) 117 | * vX.Y.Z-pre.0.yyyyddmmhhmmss-abcdefabcdef (commit after semver vX.Y.Z-pre) 118 | * vX.Y.(Z+1)-0.yyyyddmmhhmmss-abcdefabcdef (commit after semver vX.Y.Z) 119 | * tag-1.yyyyddmmhhmmss-abcdefabcdef (commit after tag) 120 | 121 | Diff mode 122 | --------- 123 | 124 | When supplying the -diff option, retrodep compares with a specific 125 | version only, and outputs the differences (in unified diff format) 126 | between the local files and the upstream files. 127 | 128 | To compare source code in src with a known upstream version of a package, use it like this: 129 | ``` 130 | $ retrodep -diff v1.2.0 github.com/example/name src 131 | ``` 132 | 133 | No output (and a zero exit code) means the source code in src matches 134 | the upstream version v1.2.0 of github.com/example/name. Otherwise, the 135 | differences in src compared to the upstream version are shown in 136 | unified diff format, and the exit code is 5. 137 | 138 | Files in src that are not in the upstream version are presented as 139 | diffs compared with "/dev/null". Files in the upstream version but not 140 | in src are ignored. 141 | 142 | Limitations 143 | ----------- 144 | 145 | The vendor directory is assumed to be complete. 146 | 147 | Original source code is assumed to be available. 148 | 149 | Only git and repositories are currently supported, and working 'git' and 'hg' executables are assumed to be available. 150 | 151 | Non-Go code is not considered, e.g. binary-only packages, or CGo. 152 | 153 | Commits with additional files (e.g. \*\_linux.go) are identified as matching when they should not. 154 | 155 | Packages vendored from forks will not have matching commits. 156 | 157 | Files marked as "export-subst" in .gitattributes files in the vendored copy are ignored. 158 | -------------------------------------------------------------------------------- /retrodep/git.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | // This file contains methods specific to working with git. 19 | 20 | import ( 21 | "bufio" 22 | "bytes" 23 | "fmt" 24 | "os" 25 | "os/exec" 26 | "path/filepath" 27 | "strings" 28 | "time" 29 | 30 | "github.com/pkg/errors" 31 | ) 32 | 33 | type gitWorkingTree struct { 34 | anyWorkingTree 35 | } 36 | 37 | // Revisions returns all revisions in the git repository, using 'git 38 | // rev-list --all'. 39 | func (g *gitWorkingTree) Revisions() ([]string, error) { 40 | stdout, stderr, err := g.run("rev-list", "--all") 41 | if err != nil { 42 | g.showOutput(stdout, stderr) 43 | return nil, err 44 | } 45 | revisions := make([]string, 0) 46 | output := bufio.NewScanner(stdout) 47 | for output.Scan() { 48 | revisions = append(revisions, strings.TrimSpace(output.Text())) 49 | } 50 | return revisions, nil 51 | } 52 | 53 | // RevisionFromTag returns the commit hash for the given tag, using 54 | // 'git rev-parse ...' 55 | func (g *gitWorkingTree) RevisionFromTag(tag string) (string, error) { 56 | stdout, stderr, err := g.run("rev-parse", tag) 57 | if err != nil { 58 | g.showOutput(stdout, stderr) 59 | return "", err 60 | } 61 | rev := strings.TrimSpace(stdout.String()) 62 | return rev, nil 63 | } 64 | 65 | // RevSync updates the working tree to reflect the revision rev, using 66 | // 'git checkout ...'. The working tree must not have been locally 67 | // modified. 68 | func (g *gitWorkingTree) RevSync(rev string) error { 69 | stdout, stderr, err := g.run("checkout", rev) 70 | if err != nil { 71 | g.showOutput(stdout, stderr) 72 | } 73 | return err 74 | } 75 | 76 | // TimeFromRevision returns the commit timestamp for the revision 77 | // rev, using 'git show -s --pretty=format:%cI ...'. 78 | func (g *gitWorkingTree) TimeFromRevision(rev string) (time.Time, error) { 79 | run := g.run 80 | var t time.Time 81 | stdout, stderr, err := run("show", "-s", "--pretty=format:%cI", rev) 82 | if err != nil { 83 | g.showOutput(stdout, stderr) 84 | return t, err 85 | } 86 | 87 | t, err = time.Parse(time.RFC3339, strings.TrimSpace(stdout.String())) 88 | return t, err 89 | } 90 | 91 | // ReachableTag returns the most recent reachable semver tag, using 92 | // 'git describe --tags --match=...', with match globs for tags that 93 | // are likely to be semvers. It returns ErrorVersionNotFound if no 94 | // suitable tag is found. 95 | func (g *gitWorkingTree) ReachableTag(rev string) (string, error) { 96 | run := g.run 97 | var tag string 98 | for _, match := range []string{"v[0-9]*", "[0-9]*"} { 99 | stdout, stderr, err := run("describe", "--tags", "--match="+match, rev) 100 | output := strings.TrimSpace(stdout.String() + stderr.String()) 101 | if err == nil { 102 | tag = output 103 | break 104 | } 105 | 106 | // Catch failures due to not finding an appropriate tag 107 | output = strings.ToLower(output) 108 | switch { 109 | // fatal: no tag exactly matches ... 110 | // fatal: no tags can describe ... 111 | // fatal: no names found, cannot describe anything. 112 | // fatal: no annotated tags can describe ... 113 | case strings.HasPrefix(output, "fatal: no tag"), 114 | strings.HasPrefix(output, "fatal: no names"), 115 | strings.HasPrefix(output, "fatal: no annotated tag"): 116 | err = ErrorVersionNotFound 117 | default: 118 | g.showOutput(stdout, stderr) 119 | } 120 | return "", err 121 | } 122 | 123 | if tag == "" { 124 | return "", ErrorVersionNotFound 125 | } 126 | 127 | log.Debugf("%s is described as %s", rev, tag) 128 | fields := strings.Split(tag, "-") 129 | if len(fields) < 3 { 130 | // This matches a tag exactly (it must not be a semver tag) 131 | return tag, nil 132 | } 133 | tag = strings.Join(fields[:len(fields)-2], "-") 134 | return tag, nil 135 | } 136 | 137 | // FileHashesFromRef parses the output of 'git ls-tree -r' to 138 | // return the file hashes for the given tag or revision ref. 139 | func (g *gitWorkingTree) FileHashesFromRef(ref, subPath string) (FileHashes, error) { 140 | args := []string{"ls-tree", "-r", ref} 141 | if subPath != "" { 142 | args = append(args, subPath) 143 | } 144 | stdout, stderr, err := g.run(args...) 145 | if err != nil { 146 | output := strings.ToLower(stdout.String() + stderr.String()) 147 | switch { 148 | case strings.HasPrefix(output, "fatal: not a valid object name "): 149 | // This is a branch name, not a tag name 150 | return nil, ErrorInvalidRef 151 | case strings.HasPrefix(output, "fatal: not a tree object"): 152 | // This ref is not present in the repo 153 | return nil, ErrorInvalidRef 154 | } 155 | 156 | g.showOutput(stdout, stderr) 157 | return nil, err 158 | } 159 | fh := make(FileHashes) 160 | scanner := bufio.NewScanner(stdout) 161 | for scanner.Scan() { 162 | line := scanner.Text() 163 | // SP SP TAB 164 | ts := strings.SplitN(line, "\t", 2) 165 | if len(ts) != 2 { 166 | return nil, fmt.Errorf("expected TAB: %s", line) 167 | } 168 | var filename string 169 | if subPath == "" { 170 | filename = ts[1] 171 | } else { 172 | filename, err = filepath.Rel(subPath, ts[1]) 173 | if err != nil { 174 | return nil, errors.Wrapf(err, "Rel(%q, %q)", 175 | subPath, ts[1]) 176 | } 177 | } 178 | fields := strings.Fields(ts[0]) 179 | if len(fields) != 3 { 180 | return nil, fmt.Errorf("expected 3 fields: %s", ts[0]) 181 | } 182 | 183 | fh[filename] = FileHash(fields[2]) 184 | } 185 | 186 | return fh, nil 187 | } 188 | 189 | type gitHasher struct{} 190 | 191 | // Hash implements the Hasher interface for git. 192 | func (g *gitHasher) Hash(relativePath, absPath string) (FileHash, error) { 193 | args := []string{"hash-object", "--path", relativePath, absPath} 194 | cmd := exec.Command(vcsGit, args...) 195 | var buf bytes.Buffer 196 | cmd.Stdout = &buf 197 | cmd.Stderr = &buf 198 | err := cmd.Run() 199 | if err != nil { 200 | os.Stderr.Write(buf.Bytes()) 201 | return FileHash(""), err 202 | } 203 | return FileHash(strings.TrimSpace(buf.String())), nil 204 | } 205 | -------------------------------------------------------------------------------- /retrodep/workingtree_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "bytes" 20 | "io" 21 | "strings" 22 | "testing" 23 | "time" 24 | 25 | "golang.org/x/tools/go/vcs" 26 | ) 27 | 28 | // mockDescribable is a mock for the Describable interface used by 29 | // PseudoVersion. 30 | type mockDescribable struct { 31 | // The Test function context 32 | t *testing.T 33 | 34 | // name of the test 35 | name string 36 | 37 | // Expected parameter for ReachableTag and TimeFromRevision 38 | rev string 39 | 40 | // Result from ReachableTag 41 | tag string 42 | tagErr error 43 | 44 | // Whether the TimeFromRevision method was called 45 | timeFromRevisionCalled bool 46 | 47 | // Result from TimeFromRevision 48 | time time.Time 49 | timeErr error 50 | } 51 | 52 | func (d *mockDescribable) ReachableTag(rev string) (string, error) { 53 | if rev != d.rev { 54 | d.t.Errorf("%s: ReachableTag called with %q but wanted %q", 55 | d.name, rev, d.rev) 56 | } 57 | 58 | return d.tag, d.tagErr 59 | } 60 | 61 | func (d *mockDescribable) TimeFromRevision(rev string) (time.Time, error) { 62 | d.timeFromRevisionCalled = true 63 | if rev != d.rev { 64 | d.t.Errorf("%s: TimeFromRevision called with %q but wanted %q", 65 | d.name, rev, d.rev) 66 | } 67 | 68 | return d.time, d.timeErr 69 | } 70 | 71 | func TestPseudoVersion(t *testing.T) { 72 | type tcase struct { 73 | m mockDescribable 74 | pv string 75 | err error 76 | timeFromRevisionCalled bool 77 | } 78 | 79 | tm := time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC) 80 | rev := "d4c3dbfa77a74ae238e401d5d2197b45f30d8513" 81 | tcases := []tcase{ 82 | tcase{ 83 | m: mockDescribable{ 84 | name: "reachable-err", 85 | tagErr: io.EOF, // random error 86 | }, 87 | err: io.EOF, // should be reported to caller 88 | }, 89 | 90 | tcase{ 91 | m: mockDescribable{ 92 | name: "time-err", 93 | tag: "v1.2.0", 94 | timeErr: io.EOF, 95 | }, 96 | timeFromRevisionCalled: true, 97 | err: io.EOF, 98 | }, 99 | 100 | tcase{ 101 | m: mockDescribable{ 102 | name: "no-reachable", 103 | tagErr: ErrorVersionNotFound, 104 | }, 105 | pv: "v0.0.0-0.20060102150405-d4c3dbfa77a7", 106 | timeFromRevisionCalled: true, 107 | }, 108 | 109 | tcase{ 110 | m: mockDescribable{ 111 | name: "reachable-nonsemver", 112 | tag: "v1.2.0beta1", 113 | }, 114 | pv: "v1.2.0beta1-1.20060102150405-d4c3dbfa77a7", 115 | timeFromRevisionCalled: true, 116 | }, 117 | 118 | tcase{ 119 | m: mockDescribable{ 120 | name: "reachable-semver", 121 | tag: "v1.2.0", 122 | }, 123 | pv: "v1.2.1-0.20060102150405-d4c3dbfa77a7", 124 | timeFromRevisionCalled: true, 125 | }, 126 | 127 | tcase{ 128 | m: mockDescribable{ 129 | name: "reachable-presemver", 130 | tag: "v1.2.0-pre1", 131 | }, 132 | pv: "v1.2.0-pre1.0.20060102150405-d4c3dbfa77a7", 133 | timeFromRevisionCalled: true, 134 | }, 135 | } 136 | 137 | for _, tc := range tcases { 138 | m := tc.m 139 | m.t = t 140 | m.rev = rev 141 | m.time = tm 142 | 143 | pv, err := PseudoVersion(&m, rev) 144 | if err != tc.err { 145 | t.Errorf("%s: got %s, want %s", m.name, err, tc.err) 146 | continue 147 | } else if pv != tc.pv { 148 | t.Errorf("%s: got %q, want %q", m.name, pv, tc.pv) 149 | } 150 | 151 | if tc.timeFromRevisionCalled != m.timeFromRevisionCalled { 152 | t.Errorf("%s: TimeFromRevision called: %t (wanted %t)", 153 | m.name, m.timeFromRevisionCalled, tc.timeFromRevisionCalled) 154 | } 155 | } 156 | } 157 | 158 | // stubWorkingTree is used to build mocks for WorkingTree. 159 | type stubWorkingTree struct{ anyWorkingTree } 160 | 161 | func (wt *stubWorkingTree) TagSync(tag string) error { 162 | return nil 163 | } 164 | 165 | func (wt *stubWorkingTree) VersionTags() ([]string, error) { 166 | return nil, nil 167 | } 168 | 169 | func (wt *stubWorkingTree) Revisions() ([]string, error) { 170 | return nil, nil 171 | } 172 | 173 | func (wt *stubWorkingTree) FileHashesFromRef(ref, subPath string) (FileHashes, error) { 174 | return make(FileHashes), nil 175 | } 176 | 177 | func (wt *stubWorkingTree) RevSync(rev string) error { 178 | return nil 179 | } 180 | 181 | func (wt *stubWorkingTree) RevisionFromTag(tag string) (string, error) { 182 | return "", nil 183 | } 184 | 185 | func (wt *stubWorkingTree) ReachableTag(rev string) (string, error) { 186 | return "", nil 187 | } 188 | 189 | func (wt *stubWorkingTree) TimeFromRevision(rev string) (time.Time, error) { 190 | return time.Time{}, nil 191 | } 192 | 193 | func (wt *stubWorkingTree) Hasher() Hasher { 194 | return &sha256Hasher{} 195 | } 196 | 197 | func TestStripImportCommentPackage(t *testing.T) { 198 | wt := &gitWorkingTree{ 199 | anyWorkingTree: anyWorkingTree{ 200 | Dir: "testdata/godep", 201 | VCS: vcs.ByCmd("git"), 202 | }, 203 | } 204 | 205 | w := bytes.NewBuffer(nil) 206 | changed, err := wt.StripImportComment("importcomment.go", w) 207 | if err != nil { 208 | t.Fatal(err) 209 | } 210 | if !changed { 211 | t.Fatalf("changed is incorrect") 212 | } 213 | 214 | if w.String() != "package foo\n" { 215 | t.Fatalf("contents incorrect: %v", w.Bytes()) 216 | } 217 | } 218 | 219 | func TestStripImportCommentNewline(t *testing.T) { 220 | wt := &gitWorkingTree{ 221 | anyWorkingTree: anyWorkingTree{ 222 | Dir: "testdata/godep", 223 | VCS: vcs.ByCmd("git"), 224 | }, 225 | } 226 | 227 | w := bytes.NewBuffer(nil) 228 | changed, err := wt.StripImportComment("nonl.go", w) 229 | if err != nil { 230 | t.Fatal(err) 231 | } 232 | if !changed { 233 | t.Fatalf("changed is incorrect") 234 | } 235 | 236 | b := w.Bytes() 237 | if b[len(b)-1] != '\n' { 238 | t.Fatalf("missing newline: %v", w.Bytes()) 239 | } 240 | 241 | w.Reset() 242 | changed, err = wt.StripImportComment("nl.go", w) 243 | if err != nil { 244 | t.Fatal(err) 245 | } 246 | if changed { 247 | t.Fatalf("changed is incorrect") 248 | } 249 | 250 | w.Reset() 251 | changed, err = wt.StripImportComment("nonl.txt", w) 252 | if err != nil { 253 | t.Fatal(err) 254 | } 255 | if changed { 256 | t.Fatalf("changed is incorrect") 257 | } 258 | } 259 | 260 | func TestDiff(t *testing.T) { 261 | defer mockExecCommand()() 262 | 263 | wt := &gitWorkingTree{ 264 | anyWorkingTree: anyWorkingTree{ 265 | Dir: "testdata/gosource", 266 | VCS: vcs.ByCmd("git"), 267 | }, 268 | } 269 | 270 | // This will be the file contents *and* the output of 'diff -u'. 271 | mockedStdout = "--- ignored.go\n+++ignored.go\n@@ -0,0 +1 @@\n+foo\n" 272 | mockedExitStatus = 1 273 | 274 | captured := &strings.Builder{} 275 | changes, err := wt.Diff(captured, "ignored.go", "ignored.go") 276 | if err != nil { 277 | t.Fatal(err) 278 | } 279 | 280 | if changes != true { 281 | t.Errorf("changes: got %t, expected %t", changes, true) 282 | } 283 | 284 | if captured.String() != mockedStdout { 285 | t.Errorf("got %q, wanted %q", captured.String(), mockedStdout) 286 | } 287 | } 288 | -------------------------------------------------------------------------------- /retrodep/hg_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "os/exec" 20 | "strings" 21 | "testing" 22 | "time" 23 | 24 | "golang.org/x/tools/go/vcs" 25 | ) 26 | 27 | func TestHgLog(t *testing.T) { 28 | defer mockExecCommand()() 29 | 30 | h := hgWorkingTree{ 31 | anyWorkingTree: anyWorkingTree{ 32 | Dir: "", 33 | VCS: vcs.ByCmd(vcsHg), 34 | }, 35 | } 36 | 37 | mockedStdout = strings.TrimSpace(` 38 | 39 | 40 | 41 | `) + "\n" 42 | _, err := h.log(nil, 1) 43 | if err == nil { 44 | t.Error("incorrect err for unexpected log output") 45 | } 46 | 47 | mockedStdout = strings.TrimSpace(` 48 | 49 | 50 | `) + "\n" 51 | _, err = h.log(nil, 1) 52 | if err == nil { 53 | t.Error("incorrect err for invalid log output") 54 | } 55 | } 56 | 57 | func TestHgRevisions(t *testing.T) { 58 | defer mockExecCommand()() 59 | 60 | wt := hgWorkingTree{ 61 | anyWorkingTree: anyWorkingTree{ 62 | Dir: "", 63 | VCS: vcs.ByCmd(vcsHg), 64 | }, 65 | } 66 | 67 | expectedRevs := []string{ 68 | "d4c3dbfa77a74ae238e401d5d2197b45f30d8513", 69 | "a2176f4275f92ceddb47cff1e363313156124bf6", 70 | } 71 | mockedStdout = strings.TrimSpace(` 72 | 73 | 74 | 75 | tip 76 | Example 77 | 2018-09-20T12:00:00+00:00 78 | example 79 | 80 | 81 | tip 82 | Example 83 | 2018-09-20T12:00:00+00:00 84 | example 85 | 86 | 87 | `) + "\n" 88 | 89 | revs, err := wt.Revisions() 90 | if err != nil { 91 | t.Fatal(err) 92 | } 93 | if len(revs) != len(expectedRevs) { 94 | t.Fatalf("wrong number of revisions: got %d, want %d", 95 | len(revs), len(expectedRevs)) 96 | } 97 | for i, rev := range expectedRevs { 98 | if revs[i] != rev { 99 | t.Fatalf("unexpected revisions: got %v, want %v", 100 | revs, expectedRevs) 101 | } 102 | } 103 | } 104 | 105 | func TestHgRevisionFromTag(t *testing.T) { 106 | defer mockExecCommand()() 107 | 108 | wt := hgWorkingTree{ 109 | anyWorkingTree: anyWorkingTree{ 110 | Dir: "", 111 | VCS: vcs.ByCmd(vcsHg), 112 | }, 113 | } 114 | 115 | expected := "d4c3dbfa77a74ae238e401d5d2197b45f30d8513" 116 | mockedStdout = strings.TrimSpace(` 117 | 118 | 119 | 120 | tip 121 | Example 122 | 2018-09-20T12:00:00+00:00 123 | example 124 | 125 | 126 | `) + "\n" 127 | rev, err := wt.RevisionFromTag("tip") 128 | if err != nil { 129 | t.Fatal(err) 130 | } 131 | 132 | if rev != expected { 133 | t.Errorf("unexpected revision: got %v, want %v", rev, expected) 134 | } 135 | } 136 | 137 | func TestHgTimeFromRevision(t *testing.T) { 138 | defer mockExecCommand()() 139 | 140 | wt := hgWorkingTree{ 141 | anyWorkingTree: anyWorkingTree{ 142 | Dir: "", 143 | VCS: vcs.ByCmd(vcsHg), 144 | }, 145 | } 146 | 147 | revision := "d4c3dbfa77a74ae238e401d5d2197b45f30d8513" 148 | mockedStdout = strings.TrimSpace(` 149 | 150 | 151 | 152 | tip 153 | Example 154 | 2018-09-20T12:00:00+00:00 155 | example 156 | 157 | 158 | `) + "\n" 159 | tm, err := wt.TimeFromRevision(revision) 160 | if err != nil { 161 | t.Fatal(err) 162 | } 163 | 164 | var expected time.Time 165 | expected.UnmarshalText([]byte("2018-09-20T12:00:00+00:00")) 166 | if !tm.Equal(expected) { 167 | t.Errorf("unexpected time: got %s, want %s", tm, expected) 168 | } 169 | } 170 | 171 | func TestHgReachableTag(t *testing.T) { 172 | defer mockExecCommand()() 173 | 174 | wt := hgWorkingTree{ 175 | anyWorkingTree: anyWorkingTree{ 176 | Dir: "", 177 | VCS: vcs.ByCmd(vcsHg), 178 | }, 179 | } 180 | 181 | type tcase struct { 182 | name string 183 | stdout string 184 | expSuccess bool 185 | expTag string 186 | } 187 | tcases := []tcase{ 188 | tcase{ 189 | name: "no-tags", 190 | stdout: ` 191 | 192 | 193 | 194 | `, 195 | expSuccess: false, 196 | }, 197 | 198 | tcase{ 199 | name: "no-semver", 200 | stdout: ` 201 | 202 | 203 | 204 | v1.0.1beta1 205 | Example 206 | 2018-09-20T12:00:00+00:00 207 | example 208 | 209 | 210 | `, 211 | expSuccess: true, 212 | expTag: "v1.0.1beta1", 213 | }, 214 | 215 | tcase{ 216 | name: "semver-after-non-semver", 217 | stdout: ` 218 | 219 | 220 | 221 | v1.0.1beta1 222 | Example 223 | 2018-09-20T12:00:00+00:00 224 | example 225 | 226 | 227 | v1.0.0 228 | Example 229 | 2018-09-20T12:00:00+00:00 230 | example 231 | 232 | 233 | `, 234 | expSuccess: true, 235 | expTag: "v1.0.0", 236 | }, 237 | } 238 | 239 | revision := "d4c3dbfa77a74ae238e401d5d2197b45f30d8513" 240 | for _, tc := range tcases { 241 | mockedStdout = strings.TrimSpace(tc.stdout) + "\n" 242 | tag, err := wt.ReachableTag(revision) 243 | if tc.expSuccess { 244 | if err != nil { 245 | t.Errorf("unexpected failure: %s: %s", tc.name, err) 246 | } else if tag != tc.expTag { 247 | t.Errorf("incorrect tag: %s: %s", tc.name, tag) 248 | } 249 | } else if err != ErrorVersionNotFound { 250 | t.Errorf("unexpected error: %s: %s", tc.name, err) 251 | } 252 | } 253 | } 254 | 255 | func TestHgErrors(t *testing.T) { 256 | defer mockExecCommand()() 257 | 258 | wt := hgWorkingTree{ 259 | anyWorkingTree: anyWorkingTree{ 260 | Dir: "", 261 | VCS: vcs.ByCmd(vcsHg), 262 | }, 263 | } 264 | 265 | mockedStderr = "abort: no repository found in '...' (.hg not found)!\n" 266 | mockedExitStatus = 255 267 | 268 | _, err := wt.Revisions() 269 | if _, ok := err.(*exec.ExitError); !ok { 270 | t.Error("Revisions: hg failure was not reported") 271 | } 272 | _, err = wt.RevisionFromTag("tip") 273 | if _, ok := err.(*exec.ExitError); !ok { 274 | t.Error("RevisionsFromTag: hg failure was not reported") 275 | } 276 | _, err = wt.TimeFromRevision("012345") 277 | if _, ok := err.(*exec.ExitError); !ok { 278 | t.Error("TimeFromRevision: hg failure was not reported") 279 | } 280 | _, err = wt.ReachableTag("012345") 281 | if _, ok := err.(*exec.ExitError); !ok { 282 | t.Error("ReachableTag: hg failure was not reported") 283 | } 284 | _, err = wt.FileHashesFromRef("012345", "") 285 | if _, ok := err.(*exec.ExitError); !ok { 286 | t.Error("FileHashesFromRef: hg failure was not reported") 287 | } 288 | } 289 | -------------------------------------------------------------------------------- /retrodep/git_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "os/exec" 20 | "strings" 21 | "testing" 22 | "time" 23 | 24 | "golang.org/x/tools/go/vcs" 25 | ) 26 | 27 | func TestGitRevisions(t *testing.T) { 28 | defer mockExecCommand()() 29 | 30 | wt := gitWorkingTree{ 31 | anyWorkingTree: anyWorkingTree{ 32 | Dir: "", 33 | VCS: vcs.ByCmd(vcsGit), 34 | }, 35 | } 36 | 37 | expectedRevs := []string{ 38 | "d4c3dbfa77a74ae238e401d5d2197b45f30d8513", 39 | "a2176f4275f92ceddb47cff1e363313156124bf6", 40 | } 41 | mockedStdout = strings.Join(expectedRevs, "\n") + "\n" 42 | 43 | revs, err := wt.Revisions() 44 | if err != nil { 45 | t.Fatal(err) 46 | } 47 | if len(revs) != len(expectedRevs) { 48 | t.Fatalf("wrong number of revisions: got %d, want %d", 49 | len(revs), len(expectedRevs)) 50 | } 51 | for i, rev := range expectedRevs { 52 | if revs[i] != rev { 53 | t.Fatalf("unexpected revisions: got %v, want %v", 54 | revs, expectedRevs) 55 | } 56 | } 57 | } 58 | 59 | func TestGitRevisionFromTag(t *testing.T) { 60 | defer mockExecCommand()() 61 | 62 | wt := gitWorkingTree{ 63 | anyWorkingTree: anyWorkingTree{ 64 | Dir: "", 65 | VCS: vcs.ByCmd(vcsGit), 66 | }, 67 | } 68 | 69 | expected := "d4c3dbfa77a74ae238e401d5d2197b45f30d8513" 70 | mockedStdout = expected + "\n" 71 | rev, err := wt.RevisionFromTag("v1.0.0") 72 | if err != nil { 73 | t.Fatal(err) 74 | } 75 | if rev != expected { 76 | t.Errorf("unexpected revision: got %v, want %v", rev, expected) 77 | } 78 | } 79 | 80 | func TestGitRevSync(t *testing.T) { 81 | defer mockExecCommand()() 82 | 83 | wt := gitWorkingTree{ 84 | anyWorkingTree: anyWorkingTree{ 85 | Dir: "", 86 | VCS: vcs.ByCmd(vcsGit), 87 | }, 88 | } 89 | 90 | revision := "d4c3dbfa77a74ae238e401d5d2197b45f30d8513" 91 | if err := wt.RevSync(revision); err != nil { 92 | t.Errorf("unexpected error: RevSync(%q): %s", revision, err) 93 | } 94 | } 95 | 96 | func TestGitTimeFromRevision(t *testing.T) { 97 | defer mockExecCommand()() 98 | 99 | wt := gitWorkingTree{ 100 | anyWorkingTree: anyWorkingTree{ 101 | Dir: "", 102 | VCS: vcs.ByCmd(vcsGit), 103 | }, 104 | } 105 | 106 | for _, stdout := range []string{ 107 | "", 108 | "warning: inexact rename detection was skipped due to too many files.", 109 | } { 110 | timeStr := []byte("2018-09-20T16:47:29+01:00") 111 | mockedStdout = string(timeStr) + "\n" 112 | mockedStderr = stdout 113 | var expected time.Time 114 | expected.UnmarshalText(timeStr) 115 | 116 | tm, err := wt.TimeFromRevision("d4c3dbfa77a74ae238e401d5d2197b45f30d8513") 117 | if err != nil { 118 | t.Error(err) 119 | continue 120 | } 121 | 122 | if !tm.Equal(expected) { 123 | t.Errorf("unexpected time: got %s, want %s", tm, expected) 124 | } 125 | } 126 | } 127 | 128 | func TestGitReachableTag(t *testing.T) { 129 | defer mockExecCommand()() 130 | 131 | wt := gitWorkingTree{ 132 | anyWorkingTree: anyWorkingTree{ 133 | Dir: "", 134 | VCS: vcs.ByCmd(vcsGit), 135 | }, 136 | } 137 | 138 | type tcase struct { 139 | name string 140 | stdout string 141 | stderr string 142 | exit int 143 | expSuccess bool 144 | expTag string 145 | } 146 | tcases := []tcase{ 147 | tcase{ 148 | name: "no-annotated-tags", 149 | stderr: "fatal: No annotated tags can describe '...'.\n", 150 | exit: 128, 151 | }, 152 | 153 | tcase{ 154 | name: "no-tags-can-describe", 155 | stderr: "fatal: No tags can describe '...'.\n", 156 | exit: 128, 157 | }, 158 | 159 | tcase{ 160 | name: "no-names-found", 161 | stderr: "fatal: No names found, cannot describe anything.\n", 162 | exit: 128, 163 | }, 164 | 165 | tcase{ 166 | name: "exact", 167 | stdout: "v1.2.0", 168 | expSuccess: true, 169 | expTag: "v1.2.0", 170 | }, 171 | 172 | // TODO: Need support for mocking multiple commands in 173 | // order to test parsing output like 174 | // v1.2.0-27-ga0220d4 175 | } 176 | 177 | revision := "d4c3dbfa77a74ae238e401d5d2197b45f30d8513" 178 | for _, tc := range tcases { 179 | mockedStdout = tc.stdout 180 | mockedStderr = tc.stderr 181 | mockedExitStatus = tc.exit 182 | tag, err := wt.ReachableTag(revision) 183 | if tc.expSuccess { 184 | if err != nil { 185 | t.Errorf("unexpected failure: %s: %s", tc.name, err) 186 | } else if tag != tc.expTag { 187 | t.Errorf("incorrect tag: %s: %s", tc.name, tag) 188 | } 189 | } else if err != ErrorVersionNotFound { 190 | t.Errorf("unexpected error: %s: %s", tc.name, err) 191 | } 192 | } 193 | } 194 | 195 | func TestGitFileHashesFromRef(t *testing.T) { 196 | defer mockExecCommand()() 197 | 198 | wt := gitWorkingTree{ 199 | anyWorkingTree: anyWorkingTree{ 200 | Dir: "", 201 | VCS: vcs.ByCmd(vcsGit), 202 | }, 203 | } 204 | 205 | mockedStdout = "what?" 206 | _, err := wt.FileHashesFromRef("HEAD", "") 207 | if err == nil { 208 | t.Error("invalid output not reported as error") 209 | } 210 | 211 | mockedStdout = strings.Join([]string{ 212 | "100644 blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391\tignored.go", 213 | "100644 blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391\tvendor/github.com/eggs/ham/ham.go", 214 | "100644 blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391\tvendor/github.com/foo/bar/bar.go", 215 | // Test we can parse filenames that include spaces 216 | "100644 blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391\tvendor/github.com/foo/bar/bar baz.go", 217 | }, "\n") + "\n" 218 | 219 | h, err := wt.FileHashesFromRef("HEAD", "") 220 | if err != nil { 221 | t.Fatal(err) 222 | } 223 | 224 | emptyhash := "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391" 225 | expected := map[string]FileHash{ 226 | "ignored.go": FileHash(emptyhash), 227 | "vendor/github.com/eggs/ham/ham.go": FileHash(emptyhash), 228 | "vendor/github.com/foo/bar/bar.go": FileHash(emptyhash), 229 | "vendor/github.com/foo/bar/bar baz.go": FileHash(emptyhash), 230 | } 231 | 232 | if len(h) != len(expected) { 233 | t.Fatalf("wrong number of files: got %d, want %d", 234 | len(h), len(expected)) 235 | } 236 | 237 | for f, hash := range expected { 238 | if h[f] != hash { 239 | t.Fatalf("wrong filehashes: got %v, want %v", 240 | h, expected) 241 | } 242 | } 243 | } 244 | 245 | func TestGitErrors(t *testing.T) { 246 | defer mockExecCommand()() 247 | 248 | wt := gitWorkingTree{ 249 | anyWorkingTree: anyWorkingTree{ 250 | Dir: "", 251 | VCS: vcs.ByCmd(vcsGit), 252 | }, 253 | } 254 | 255 | mockedStderr = "fatal: not a git repository\n" 256 | mockedExitStatus = 128 257 | 258 | _, err := wt.Revisions() 259 | if err == nil { 260 | t.Fatal("git failure was not reported") 261 | } 262 | _, err = wt.RevisionFromTag("tip") 263 | if _, ok := err.(*exec.ExitError); !ok { 264 | t.Error("RevisionsFromTag: git failure was not reported") 265 | } 266 | err = wt.RevSync("tip") 267 | if _, ok := err.(*exec.ExitError); !ok { 268 | t.Error("RevSync: git failure was not reported") 269 | } 270 | _, err = wt.TimeFromRevision("012345") 271 | if _, ok := err.(*exec.ExitError); !ok { 272 | t.Error("TimeFromRevision: git failure was not reported") 273 | } 274 | _, err = wt.ReachableTag("012345") 275 | if _, ok := err.(*exec.ExitError); !ok { 276 | t.Error("ReachableTag: git failure was not reported") 277 | } 278 | _, err = wt.FileHashesFromRef("012345", "") 279 | if _, ok := err.(*exec.ExitError); !ok { 280 | t.Error("FileHashesFromRef: git failure was not reported") 281 | } 282 | 283 | mockedStderr = "fatal: Not a valid object name 012345\n" 284 | _, err = wt.FileHashesFromRef("012345", "") 285 | if err != ErrorInvalidRef { 286 | t.Error("FileHashesFromRef: missing ErrorInvalidRef") 287 | } 288 | 289 | mockedStderr = "fatal: not a tree object\n" 290 | _, err = wt.FileHashesFromRef("012345", "") 291 | if err != ErrorInvalidRef { 292 | t.Error("FileHashesFromRef: missing ErrorInvalidRef") 293 | } 294 | 295 | hasher := &gitHasher{} 296 | _, err = hasher.Hash("", "") 297 | if _, ok := err.(*exec.ExitError); !ok { 298 | t.Error("Hash: git failure was not reported") 299 | } 300 | } 301 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package main 17 | 18 | import ( 19 | "bufio" 20 | "flag" 21 | "fmt" 22 | "io/ioutil" 23 | "os" 24 | "path/filepath" 25 | "sort" 26 | "strings" 27 | "text/template" 28 | 29 | "github.com/op/go-logging" 30 | "github.com/release-engineering/retrodep/v2/retrodep" 31 | "golang.org/x/tools/go/vcs" 32 | ) 33 | 34 | const defaultTemplate string = ` 35 | {{- if .TopPkg -}} 36 | {{.TopPkg}}:{{or .TopVer "?"}} {{ end -}} 37 | {{.Pkg}}:{{or .Ver "?"}}` 38 | 39 | var log = logging.MustGetLogger("retrodep") 40 | 41 | var helpFlag = flag.Bool("help", false, "print help") 42 | var importPath = flag.String("importpath", "", "top-level import path") 43 | var onlyImportPath = flag.Bool("only-importpath", false, "only show the top-level import path") 44 | var depsFlag = flag.Bool("deps", true, "show vendored dependencies") 45 | var diffArg = flag.String("diff", "", "compare with upstream ref (implies -deps=false)") 46 | var excludeFrom = flag.String("exclude-from", "", "ignore directory entries matching globs in `exclusions`") 47 | var debugFlag = flag.Bool("debug", false, "show debugging output") 48 | var outputArg = flag.String("o", "", "output format, one of: go-template=...") 49 | var templateArg = flag.String("template", "", "go template to use for output with Pkg, Repo, Rev, Tag and Ver (deprecated)") 50 | var exitFirst = flag.Bool("x", false, "exit on the first failure") 51 | 52 | var errorShown = false 53 | var usage func(string) 54 | 55 | func displayUnknown(tmpl *template.Template, topLevelMarker string, ref *retrodep.Reference, projectRoot string) { 56 | if ref == nil || *templateArg != "" { 57 | fmt.Printf("%s%s ?\n", topLevelMarker, projectRoot) 58 | } else { 59 | display(tmpl, topLevelMarker, ref) 60 | } 61 | if !errorShown { 62 | errorShown = true 63 | fmt.Fprintln(os.Stderr, "error: not all versions identified") 64 | if *exitFirst { 65 | os.Exit(2) 66 | } 67 | } 68 | } 69 | 70 | func display(tmpl *template.Template, topLevelMarker string, ref *retrodep.Reference) { 71 | var builder strings.Builder 72 | builder.WriteString(topLevelMarker) 73 | err := tmpl.Execute(&builder, ref) 74 | if err != nil { 75 | log.Fatalf("Error generating output. %s", err) 76 | } 77 | fmt.Println(builder.String()) 78 | } 79 | 80 | func getProject(src *retrodep.GoSource, importPath string) *retrodep.RepoPath { 81 | main, err := src.Project(importPath) 82 | if err != nil { 83 | if err == retrodep.ErrorNeedImportPath { 84 | log.Errorf("%s: %s", src.Path, err) 85 | fmt.Fprintln(os.Stderr, 86 | "Provide import path with -importpath") 87 | os.Exit(3) 88 | } 89 | log.Fatalf("%s: %s", src.Path, err) 90 | } 91 | 92 | return main 93 | } 94 | 95 | // newWorkingTree creates a new retrodep.WorkingTree for the path. 96 | func newWorkingTree(path string, project *vcs.RepoRoot) (wt retrodep.WorkingTree, err error) { 97 | wt, err = retrodep.NewWorkingTree(project) 98 | if err != nil { 99 | log.Errorf("%s: %s, retrying", path, err) 100 | wt, err = retrodep.NewWorkingTree(project) 101 | } 102 | return 103 | } 104 | 105 | func showTopLevel(tmpl *template.Template, src *retrodep.GoSource) *retrodep.Reference { 106 | var topLevelMarker string 107 | if *templateArg != "" { 108 | topLevelMarker = "*" 109 | } 110 | main := getProject(src, *importPath) 111 | if main.Err != nil { 112 | log.Errorf("%s: %s", *importPath, main.Err) 113 | displayUnknown(tmpl, topLevelMarker, nil, main.Root) 114 | return nil 115 | } 116 | 117 | wt, err := newWorkingTree(src.Path, &main.RepoRoot) 118 | if err != nil { 119 | log.Errorf("%s: %s", src.Path, err) 120 | 121 | // Treat this as VersionNotFound. 122 | project := &retrodep.Reference{ 123 | Pkg: main.Root, 124 | Repo: main.Repo, 125 | } 126 | displayUnknown(tmpl, topLevelMarker, project, main.Root) 127 | return project 128 | } 129 | 130 | defer wt.Close() 131 | project, err := src.DescribeProject(main, wt, src.Path, nil) 132 | switch err { 133 | case retrodep.ErrorVersionNotFound: 134 | displayUnknown(tmpl, topLevelMarker, project, main.Root) 135 | case nil: 136 | display(tmpl, topLevelMarker, project) 137 | default: 138 | log.Fatalf("%s: %s", src.Path, err) 139 | } 140 | 141 | return project 142 | } 143 | 144 | func showVendored(tmpl *template.Template, src *retrodep.GoSource, top *retrodep.Reference) { 145 | vendored, err := src.VendoredProjects() 146 | if err != nil { 147 | log.Fatal(err) 148 | } 149 | 150 | // Sort the projects for predictable output 151 | var repos []string 152 | for repo := range vendored { 153 | repos = append(repos, repo) 154 | } 155 | sort.Strings(repos) 156 | 157 | // Describe each vendored project 158 | for _, repo := range repos { 159 | project := vendored[repo] 160 | if project.Err != nil { 161 | log.Errorf("%s: %s", repo, project.Err) 162 | ref := &retrodep.Reference{ 163 | TopPkg: top.Pkg, 164 | TopVer: top.Ver, 165 | Pkg: repo, 166 | } 167 | displayUnknown(tmpl, "", ref, repo) 168 | continue 169 | } 170 | 171 | wt, err := newWorkingTree(project.Root, &project.RepoRoot) 172 | if err != nil { 173 | log.Errorf("%s: %s", project.Root, err) 174 | 175 | // Treat this as VersionNotFound. 176 | vp := &retrodep.Reference{ 177 | TopPkg: top.Pkg, 178 | TopVer: top.Ver, 179 | Pkg: project.Root, 180 | Repo: project.Repo, 181 | } 182 | displayUnknown(tmpl, "", vp, project.Root) 183 | continue 184 | } 185 | 186 | defer wt.Close() 187 | vp, err := src.DescribeVendoredProject(project, wt, top) 188 | switch err { 189 | case retrodep.ErrorVersionNotFound: 190 | displayUnknown(tmpl, "", vp, project.Root) 191 | case nil: 192 | display(tmpl, "", vp) 193 | default: 194 | log.Fatalf("%s: %s", project.Root, err) 195 | } 196 | } 197 | } 198 | 199 | func readExcludeFile() []string { 200 | if *excludeFrom == "" { 201 | return nil 202 | } 203 | 204 | e, err := os.Open(*excludeFrom) 205 | if err != nil { 206 | log.Fatal(err) 207 | } 208 | defer e.Close() 209 | 210 | excludes := make([]string, 0) 211 | scanner := bufio.NewScanner(bufio.NewReader(e)) 212 | for scanner.Scan() { 213 | excludes = append(excludes, strings.TrimSpace(scanner.Text())) 214 | } 215 | return excludes 216 | } 217 | 218 | func processArgs(args []string) []*retrodep.GoSource { 219 | progName := filepath.Base(args[0]) 220 | 221 | // Stop the default behaviour of printing errors and exiting. 222 | // Instead, silence the printing and return them. 223 | cli := flag.CommandLine 224 | cli.Init("", flag.ContinueOnError) 225 | cli.SetOutput(ioutil.Discard) 226 | cli.Usage = func() {} 227 | 228 | usageMsg := fmt.Sprintf("usage: %s [OPTION]... PATH", progName) 229 | usage = func(flaw string) { 230 | log.Fatalf("%s: %s\n%s", progName, flaw, usageMsg) 231 | } 232 | err := cli.Parse(args[1:]) 233 | if err == flag.ErrHelp || *helpFlag { // Handle ‘-h’. 234 | fmt.Printf("%s: help requested\n%s\n", progName, usageMsg) 235 | cli.SetOutput(os.Stdout) 236 | flag.PrintDefaults() 237 | os.Exit(0) // Not an error. 238 | } 239 | if err != nil { 240 | usage(err.Error()) 241 | } 242 | 243 | narg := flag.NArg() 244 | if narg == 0 { 245 | usage("missing path") 246 | } 247 | if narg != 1 { 248 | usage(fmt.Sprintf("only one path allowed: %q", flag.Arg(1))) 249 | } 250 | 251 | level := logging.INFO 252 | if *debugFlag { 253 | level = logging.DEBUG 254 | } 255 | logging.SetLevel(level, "retrodep") 256 | 257 | excludeGlobs := readExcludeFile() 258 | path := flag.Arg(0) 259 | sources, err := retrodep.FindGoSources(path, excludeGlobs) 260 | if err != nil { 261 | if err == retrodep.ErrorNoGo { 262 | fmt.Fprintf(os.Stderr, 263 | "%s: no Go source code at %s\n", 264 | progName, path) 265 | os.Exit(4) 266 | } 267 | 268 | log.Fatal(err) 269 | } 270 | 271 | return sources 272 | } 273 | 274 | func getTemplate() string { 275 | var customTemplate string 276 | switch { 277 | case *outputArg != "": 278 | customTemplate = strings.TrimPrefix(*outputArg, "go-template=") 279 | if customTemplate == *outputArg { 280 | usage("unknown output format") 281 | } 282 | case *templateArg != "": 283 | customTemplate = "{{.Pkg}}" + *templateArg 284 | log.Warning("-template is deprecated, use -o go-template= instead") 285 | default: 286 | customTemplate = defaultTemplate 287 | } 288 | 289 | return customTemplate 290 | } 291 | 292 | func main() { 293 | srcs := processArgs(os.Args) 294 | 295 | customTemplate := getTemplate() 296 | tmpl, err := template.New("output").Parse(customTemplate) 297 | if err != nil { 298 | log.Fatal(err) 299 | } 300 | changes := false 301 | for _, src := range srcs { 302 | if *diffArg != "" { 303 | main := getProject(src, *importPath) 304 | 305 | wt, err := newWorkingTree(src.Path, &main.RepoRoot) 306 | if err != nil { 307 | log.Fatal(err) 308 | } 309 | defer wt.Close() 310 | 311 | c, err := src.Diff(main, wt, os.Stdout, src.Path, *diffArg) 312 | if err != nil { 313 | log.Fatal(err) 314 | } 315 | 316 | changes = changes || c 317 | } else if *onlyImportPath { 318 | main := getProject(src, *importPath) 319 | fmt.Println("*" + main.Root) 320 | } else { 321 | top := showTopLevel(tmpl, src) 322 | if *depsFlag { 323 | showVendored(tmpl, src, top) 324 | } 325 | } 326 | } 327 | 328 | if errorShown { 329 | os.Exit(2) 330 | } 331 | 332 | if *diffArg != "" && changes { 333 | os.Exit(5) 334 | } 335 | } 336 | -------------------------------------------------------------------------------- /retrodep/gosource_test.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "os" 20 | "strings" 21 | "testing" 22 | 23 | "golang.org/x/tools/go/vcs" 24 | ) 25 | 26 | func TestFindExcludes(t *testing.T) { 27 | type tcase struct { 28 | dir string 29 | globs []string 30 | exp []string 31 | } 32 | tcases := []tcase{ 33 | tcase{ 34 | dir: "testdata/gosource", 35 | globs: nil, 36 | exp: []string{}, 37 | }, 38 | 39 | tcase{ 40 | dir: "testdata/gosource", 41 | globs: []string{"vendor*"}, 42 | exp: []string{"testdata/gosource/vendor"}, 43 | }, 44 | } 45 | for _, tc := range tcases { 46 | excl, err := FindExcludes(tc.dir, tc.globs) 47 | if err != nil { 48 | t.Fatal(err) 49 | } 50 | if len(tc.exp) != len(excl) { 51 | t.Errorf("wrong length: got %d, want %d", len(excl), len(tc.exp)) 52 | } 53 | for i, e := range tc.exp { 54 | if excl[i] != e { 55 | t.Errorf("wrong value: got %v, want %v", excl, tc.exp) 56 | break 57 | } 58 | } 59 | } 60 | } 61 | 62 | func TestNewGoSource(t *testing.T) { 63 | type tcase struct { 64 | path string 65 | pkg string 66 | expOk bool 67 | } 68 | tcases := []tcase{ 69 | tcase{"testdata/gosource", "", true}, 70 | tcase{"testdata/godep", "example.com/godep", true}, 71 | tcase{"testdata/importcomment", "importcomment", true}, 72 | tcase{"testdata/importcommentsub", "importcomment", true}, 73 | tcase{"testdata", "", false}, 74 | } 75 | for _, tc := range tcases { 76 | s, err := NewGoSource(tc.path, nil) 77 | ok := err == nil 78 | if ok != tc.expOk { 79 | t.Errorf("%s: got %s, want ok:%t", 80 | tc.path, err, tc.expOk) 81 | } 82 | 83 | if err != nil { 84 | continue 85 | } 86 | 87 | if s.Package != tc.pkg { 88 | t.Errorf("%s: got package %q, want %q", 89 | tc.path, s.Package, tc.pkg) 90 | } 91 | } 92 | } 93 | 94 | func TestFindGoSources(t *testing.T) { 95 | type exp struct { 96 | path, subpath string 97 | } 98 | type tcase struct { 99 | name string 100 | path string 101 | exp []exp 102 | } 103 | tcases := []tcase{ 104 | tcase{ 105 | name: "single", 106 | path: "testdata/gosource", 107 | exp: []exp{{"testdata/gosource", ""}}, 108 | }, 109 | 110 | tcase{ 111 | name: "multi", 112 | path: "testdata/multi", 113 | exp: []exp{ 114 | {"testdata/multi/abc", "abc"}, 115 | {"testdata/multi/def", "def"}, 116 | }, 117 | }, 118 | } 119 | for _, tc := range tcases { 120 | srcs, err := FindGoSources(tc.path, nil) 121 | if err != nil { 122 | t.Errorf("%s: %s", tc.name, err) 123 | continue 124 | } 125 | if srcs == nil { 126 | t.Errorf("%s: srcs is nil", tc.name) 127 | continue 128 | } 129 | if len(srcs) != len(tc.exp) { 130 | t.Errorf("%s: got %d sources, want %d", tc.name, len(srcs), len(tc.exp)) 131 | continue 132 | } 133 | for i, src := range tc.exp { 134 | if src.path != srcs[i].Path { 135 | t.Errorf("%s: Path: got %q, want %q", tc.name, srcs[i].Path, src.path) 136 | } 137 | if src.subpath != srcs[i].SubPath { 138 | t.Errorf("%s: SubPath: got %q, want %q", tc.name, srcs[i].SubPath, src.subpath) 139 | } 140 | } 141 | } 142 | } 143 | 144 | func TestProject(t *testing.T) { 145 | type tcase struct { 146 | name string 147 | importPath string 148 | root string 149 | expSubPath string 150 | } 151 | tcases := []tcase{ 152 | tcase{ 153 | name: "trivial", 154 | importPath: "example.com/foo", 155 | root: "example.com/foo", 156 | expSubPath: "", 157 | }, 158 | 159 | tcase{ 160 | name: "subdir", 161 | importPath: "example.com/foo/bar", 162 | root: "example.com/foo", 163 | expSubPath: "bar", 164 | }, 165 | } 166 | src, err := NewGoSource("testdata/gosource", nil) 167 | if err != nil { 168 | t.Fatal(err) 169 | } 170 | 171 | // Reset vcsRepoRootForImportPath after this test. 172 | defer func() { 173 | vcsRepoRootForImportPath = vcs.RepoRootForImportPath 174 | }() 175 | 176 | for _, tc := range tcases { 177 | vcsRepoRootForImportPath = func(importPath string, _ bool) (*vcs.RepoRoot, error) { 178 | return &vcs.RepoRoot{ 179 | Root: tc.root, 180 | }, nil 181 | } 182 | 183 | repoPath, err := src.Project(tc.importPath) 184 | if err != nil { 185 | t.Errorf("%s: %s", tc.name, err) 186 | continue 187 | } 188 | if repoPath.SubPath != tc.expSubPath { 189 | t.Errorf("%s: SubPath: want %q, got %q", tc.name, repoPath.SubPath, 190 | tc.expSubPath) 191 | } 192 | } 193 | } 194 | 195 | func TestDirs(t *testing.T) { 196 | src, err := NewGoSource("testdata/gosource", nil) 197 | if err != nil { 198 | t.Fatal(err) 199 | } 200 | if src.Path != "testdata/gosource" { 201 | t.Fatal("Path") 202 | } 203 | if src.Vendor() != "testdata/gosource/vendor" { 204 | t.Fatal("Vendor") 205 | } 206 | } 207 | 208 | func TestGodepFalse(t *testing.T) { 209 | src, err := NewGoSource("testdata/gosource", nil) 210 | if err != nil { 211 | t.Fatal(err) 212 | } 213 | if src.usesGodep { 214 | t.Fatal("usesGodep") 215 | } 216 | } 217 | 218 | func TestGodepTrue(t *testing.T) { 219 | src, err := NewGoSource("testdata/godep", nil) 220 | if err != nil { 221 | t.Fatal(err) 222 | } 223 | if !src.usesGodep { 224 | t.Fatal("usesGodep") 225 | } 226 | exp := "example.com/godep" 227 | if src.Package != exp { 228 | t.Errorf("wrong import path detected: want %s, got %s", 229 | exp, src.Package) 230 | } 231 | } 232 | 233 | func TestGlideFalse(t *testing.T) { 234 | src, err := NewGoSource("testdata/godep", nil) 235 | if err != nil { 236 | t.Fatal(err) 237 | } 238 | if src.Package == "github.com/release-engineering/retrodep/testdata/glide" { 239 | t.Fatal("usesGlide") 240 | } 241 | } 242 | 243 | func TestGlideTrue(t *testing.T) { 244 | src, err := NewGoSource("testdata/glide", nil) 245 | if err != nil { 246 | t.Fatal(err) 247 | } 248 | if src.Package != "github.com/release-engineering/retrodep/testdata/glide" { 249 | t.Fatal("usesGodep") 250 | } 251 | } 252 | 253 | func TestImportPathFromFilepath(t *testing.T) { 254 | tests := []struct { 255 | name string 256 | filePath, importPath string 257 | ok bool 258 | }{ 259 | { 260 | "toplevel", 261 | "/home/foo/github.com/release-engineering/retrodep", 262 | "github.com/release-engineering/retrodep", 263 | true, 264 | }, 265 | { 266 | "subdir", 267 | "/home/foo/github.com/release-engineering/retrodep/retrodep", 268 | "github.com/release-engineering/retrodep/retrodep", 269 | true, 270 | }, 271 | { 272 | "trailing-slash", 273 | "/home/foo/github.com/release-engineering/retrodep/", 274 | "github.com/release-engineering/retrodep", 275 | true, 276 | }, 277 | { 278 | "unknown", 279 | "release-engineering/retrodep", 280 | "", 281 | false, 282 | }, 283 | } 284 | 285 | // Start in the root directory to make sure Abs doesn't figure 286 | // anything out from the path to the project we're in. 287 | wd, err := os.Getwd() 288 | if err != nil { 289 | t.Fatal(err) 290 | } 291 | defer os.Chdir(wd) 292 | err = os.Chdir("/") 293 | if err != nil { 294 | t.Fatal(err) 295 | } 296 | 297 | for _, test := range tests { 298 | importPath, ok := importPathFromFilepath(test.filePath) 299 | if ok != test.ok { 300 | t.Errorf("%s: wrong ok value for %s: got _,%v, want _,%v", 301 | test.name, test.filePath, ok, test.ok) 302 | continue 303 | } 304 | if !ok { 305 | continue 306 | } 307 | 308 | if importPath != test.importPath { 309 | t.Errorf("%s: wrong path for %s: got %q, want %q", 310 | test.name, test.filePath, importPath, test.importPath) 311 | } 312 | } 313 | } 314 | 315 | type mockWorkingTree struct{ stubWorkingTree } 316 | 317 | func (m *mockWorkingTree) FileHashesFromRef(ref, subPath string) (FileHashes, error) { 318 | hashes := make(FileHashes) 319 | // This is the correct hash for nl.go: 320 | hashes["nl.go"] = "4ccdb7b17d6eaf1b51ed56932c020edcf323fd5734ce32d01a2713edeb17f6da" 321 | return hashes, nil 322 | } 323 | 324 | func TestGoSourceDiff(t *testing.T) { 325 | dir := "testdata/godep" 326 | src, err := NewGoSource(dir, nil) 327 | if err != nil { 328 | t.Fatal(err) 329 | } 330 | 331 | // Reset vcsRepoRootForImportPath after this test. 332 | defer func() { 333 | vcsRepoRootForImportPath = vcs.RepoRootForImportPath 334 | }() 335 | 336 | vcsRepoRootForImportPath = func(importPath string, _ bool) (*vcs.RepoRoot, error) { 337 | return &vcs.RepoRoot{ 338 | Root: "example.com/foo/bar", 339 | }, nil 340 | } 341 | 342 | project, err := src.Project("example.com/foo/bar") 343 | if err != nil { 344 | t.Fatal(err) 345 | } 346 | 347 | wt := &mockWorkingTree{ 348 | stubWorkingTree: stubWorkingTree{ 349 | anyWorkingTree: anyWorkingTree{ 350 | hasher: &sha256Hasher{}, 351 | }, 352 | }, 353 | } 354 | 355 | writer := &strings.Builder{} 356 | changes, err := src.Diff(project, wt, writer, dir, "v1.0.0") 357 | if err != nil { 358 | t.Fatal(err) 359 | } 360 | 361 | if changes != true { 362 | t.Errorf("changes: got %t but expected %t", changes, true) 363 | } 364 | 365 | // Find which files are in the diff output. 366 | output := writer.String() 367 | lines := strings.Split(output, "\n") 368 | newFiles := make(map[string]struct{}) 369 | for _, line := range lines { 370 | if !strings.HasPrefix(line, "+++ ") { 371 | continue 372 | } 373 | 374 | fields := strings.Split(line[4:], "\t") 375 | newFiles[fields[0]] = struct{}{} 376 | } 377 | 378 | expected := []string{ 379 | "testdata/godep/Godeps/Godeps.json", 380 | "testdata/godep/importcomment.go", 381 | "testdata/godep/nonl.go", 382 | "testdata/godep/nonl.txt", 383 | } 384 | for _, expect := range expected { 385 | if _, ok := newFiles[expect]; !ok { 386 | t.Errorf("missing: %s", expect) 387 | } 388 | } 389 | if len(expected) != len(newFiles) { 390 | t.Errorf("got %d, expected %d", len(newFiles), len(expected)) 391 | } 392 | } 393 | -------------------------------------------------------------------------------- /retrodep/workingtree.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "bufio" 20 | "bytes" 21 | "io" 22 | "io/ioutil" 23 | "os" 24 | "os/exec" 25 | "path/filepath" 26 | "regexp" 27 | "sort" 28 | "strings" 29 | "syscall" 30 | "time" 31 | 32 | "github.com/Masterminds/semver" 33 | "github.com/pkg/errors" 34 | "golang.org/x/tools/go/vcs" 35 | ) 36 | 37 | var execCommand = exec.Command 38 | 39 | // Describable is the interface which capture the methods required for 40 | // creating a pseudo-version from a revision. 41 | type Describable interface { 42 | // ReachableTag returns the most recent reachable tag, 43 | // preferring semver tags. It returns ErrorVersionNotFound if 44 | // no suitable tag is found. 45 | ReachableTag(rev string) (string, error) 46 | 47 | // TimeFromRevision returns the commit timestamp from the 48 | // revision rev. 49 | TimeFromRevision(rev string) (time.Time, error) 50 | } 51 | 52 | // A WorkingTree is a local checkout of Go source code, and methods to 53 | // interact with the version control system it came from. 54 | type WorkingTree interface { 55 | io.Closer 56 | 57 | // Should be something that supports creating pseudo-versions. 58 | Describable 59 | 60 | // Should be something that supports hashing files. 61 | Hasher 62 | 63 | // TagSync syncs the repo to the named tag. 64 | TagSync(tag string) error 65 | 66 | // VersionTags returns the semantic version tags. 67 | VersionTags() ([]string, error) 68 | 69 | // Revisions returns all revisions, newest to oldest. 70 | Revisions() ([]string, error) 71 | 72 | // FileHashesFromRef returns the file hashes for the tag or 73 | // revision ref. The returned FileHashes will be relative to 74 | // the subPath, which is itself relative to the repository 75 | // root. 76 | FileHashesFromRef(ref, subPath string) (FileHashes, error) 77 | 78 | // RevSync syncs the repo to the named revision. 79 | RevSync(rev string) error 80 | 81 | // RevisionFromTag returns the revision ID from the tag. 82 | RevisionFromTag(tag string) (string, error) 83 | 84 | // StripImportComment removes import comments from package 85 | // declarations in the same way godep does, writing the result 86 | // (if changed) to w. It returns a boolean indicating whether 87 | // an import comment was removed. 88 | // 89 | // The file content may be written to w even if no change was made. 90 | StripImportComment(path string, w io.Writer) (bool, error) 91 | 92 | // Diff writes output to out from 'diff -u' comparing the 93 | // path within the working tree with the localFile. It returns 94 | // true if changes were found and false if not. 95 | Diff(out io.Writer, path, localFile string) (bool, error) 96 | } 97 | 98 | // anyWorkingTree uses the golang.org/x/tools/go/vcs Cmd type for 99 | // interacting with the working tree. Other types build on this to 100 | // provide methods not handled by vcs.Cmd. 101 | type anyWorkingTree struct { 102 | Dir string 103 | VCS *vcs.Cmd 104 | hasher Hasher 105 | } 106 | 107 | // NewWorkingTree creates a local checkout of the version control 108 | // system for a Go project. 109 | func NewWorkingTree(project *vcs.RepoRoot) (WorkingTree, error) { 110 | dir, err := ioutil.TempDir("", "retrodep.") 111 | if err != nil { 112 | return nil, err 113 | } 114 | 115 | err = project.VCS.Create(dir, project.Repo) 116 | if err != nil { 117 | os.RemoveAll(dir) 118 | return nil, err 119 | } 120 | 121 | wt := anyWorkingTree{ 122 | Dir: dir, 123 | VCS: project.VCS, 124 | } 125 | switch project.VCS.Cmd { 126 | case vcsGit: 127 | wt.hasher = &gitHasher{} 128 | return &gitWorkingTree{anyWorkingTree: wt}, nil 129 | case vcsHg: 130 | wt.hasher = &sha256Hasher{} 131 | return &hgWorkingTree{anyWorkingTree: wt}, nil 132 | } 133 | 134 | wt.Close() 135 | return nil, ErrorUnknownVCS 136 | } 137 | 138 | // Close removes the local checkout. 139 | func (wt *anyWorkingTree) Close() error { 140 | return os.RemoveAll(wt.Dir) 141 | } 142 | 143 | func (wt *anyWorkingTree) TagSync(tag string) error { 144 | return wt.VCS.TagSync(wt.Dir, tag) 145 | } 146 | 147 | // VersionTags returns the tags that are parseable as semantic tags, 148 | // e.g. v1.1.0. 149 | func (wt *anyWorkingTree) VersionTags() ([]string, error) { 150 | tags, err := wt.VCS.Tags(wt.Dir) 151 | if err != nil { 152 | return nil, err 153 | } 154 | versions := make(semver.Collection, 0) 155 | versionTags := make(map[*semver.Version]string) 156 | for _, tag := range tags { 157 | v, err := semver.NewVersion(tag) 158 | if err != nil { 159 | continue 160 | } 161 | versions = append(versions, v) 162 | versionTags[v] = tag 163 | } 164 | sort.Sort(sort.Reverse(versions)) 165 | strTags := make([]string, len(versions)) 166 | for i, v := range versions { 167 | strTags[i] = versionTags[v] 168 | } 169 | return strTags, nil 170 | } 171 | 172 | // run runs the VCS command with the provided args 173 | // and returns stdout and stderr (as bytes.Buffer). 174 | func (wt *anyWorkingTree) run(args ...string) (*bytes.Buffer, *bytes.Buffer, error) { 175 | p := execCommand(wt.VCS.Cmd, args...) 176 | var stdout, stderr bytes.Buffer 177 | p.Stdout = &stdout 178 | p.Stderr = &stderr 179 | p.Dir = wt.Dir 180 | err := p.Run() 181 | return &stdout, &stderr, err 182 | } 183 | 184 | // showOutput writes stdout to os.Stdout and stderr to os.Stderr. 185 | func (wt *anyWorkingTree) showOutput(stdout, stderr *bytes.Buffer) { 186 | os.Stdout.Write(stdout.Bytes()) 187 | os.Stderr.Write(stderr.Bytes()) 188 | } 189 | 190 | // PseudoVersion returns a semantic-like comparable version for a 191 | // revision, based on tags reachable from that revision. 192 | func PseudoVersion(d Describable, rev string) (string, error) { 193 | suffix := "-0." // This commit is *before* some other tag 194 | var version string 195 | reachable, err := d.ReachableTag(rev) 196 | if err == ErrorVersionNotFound { 197 | version = "v0.0.0" 198 | } else if err != nil { 199 | return "", err 200 | } else { 201 | ver, err := semver.NewVersion(reachable) 202 | if err != nil { 203 | // Not a semantic version. Use a timestamped suffix 204 | // to indicate this commit is *after* the tag 205 | version = reachable 206 | suffix = "-1." 207 | } else { 208 | if ver.Prerelease() == "" { 209 | *ver = ver.IncPatch() 210 | } else { 211 | suffix = ".0." 212 | } 213 | 214 | version = "v" + ver.String() 215 | } 216 | } 217 | 218 | t, err := d.TimeFromRevision(rev) 219 | if err != nil { 220 | return "", err 221 | } 222 | 223 | timestamp := t.Format("20060102150405") 224 | pseudo := version + suffix + timestamp + "-" + rev[:12] 225 | return pseudo, nil 226 | } 227 | 228 | const quotedRE = `(?:"[^"]+"|` + "`[^`]+`)" 229 | const importRE = `\s*import\s+` + quotedRE + `\s*` 230 | 231 | var importCommentRE = regexp.MustCompile( 232 | `^(package\s+\w+)\s+(?://` + importRE + `$|/\*` + importRE + `\*/)(.*)`, 233 | ) 234 | 235 | func removeImportComment(line []byte) []byte { 236 | if matches := importCommentRE.FindSubmatch(line); matches != nil { 237 | return append( 238 | matches[1], // package statement 239 | matches[2]...) // comments after first closing "*/" 240 | } 241 | 242 | return nil 243 | } 244 | 245 | // StripImportComment removes import comments from package 246 | // declarations in the same way godep does, writing the result (if 247 | // changed) to w. It returns a boolean indicating whether an import 248 | // comment was removed. 249 | // 250 | // The file content may be written to w even if no change was made. 251 | func (wt *anyWorkingTree) StripImportComment(path string, w io.Writer) (bool, error) { 252 | if !strings.HasSuffix(path, ".go") { 253 | return false, nil 254 | } 255 | path = filepath.Join(wt.Dir, path) 256 | r, err := os.Open(path) 257 | if err != nil { 258 | return false, errors.Wrap(err, "StripImportComment") 259 | } 260 | defer r.Close() 261 | 262 | b := bufio.NewReader(r) 263 | changed := false 264 | eof := false 265 | for !eof { 266 | line, err := b.ReadBytes('\n') 267 | if err != nil { 268 | if err == io.EOF { 269 | eof = true 270 | } else { 271 | return false, errors.Wrap(err, "StripImportComment") 272 | } 273 | } 274 | if len(line) > 0 { 275 | nonl := bytes.TrimRight(line, "\n") 276 | if len(nonl) == len(line) { 277 | // There was no newline but we'll add one 278 | changed = true 279 | } 280 | repl := removeImportComment(nonl) 281 | if repl != nil { 282 | nonl = repl 283 | changed = true 284 | } 285 | 286 | if _, err := w.Write(append(nonl, '\n')); err != nil { 287 | return false, errors.Wrap(err, "StripImportComment") 288 | } 289 | } 290 | } 291 | 292 | return changed, nil 293 | } 294 | 295 | // Hash returns the file hash for the filename absPath, hashed as 296 | // though it were in the repository as filename relativePath. 297 | func (wt *anyWorkingTree) Hash(relativePath, absPath string) (FileHash, error) { 298 | return wt.hasher.Hash(relativePath, absPath) 299 | } 300 | 301 | // Diff writes output to stdout from 'diff -u' comparing the 302 | // path within the working tree with the localFile. It returns 303 | // true if changes were found and false if not. 304 | func (wt *anyWorkingTree) Diff(out io.Writer, path, localFile string) (bool, error) { 305 | if path == "" { 306 | path = "/dev/null" 307 | } else if path[0] != '/' { 308 | path = filepath.Join(wt.Dir, path) 309 | } 310 | 311 | p := execCommand("diff", "-u", path, localFile) 312 | p.Stdout = out 313 | err := p.Run() 314 | 315 | changes := false 316 | if err != nil { 317 | // Find the exit code from an exec.ExitError by using 318 | // the embedded os.ProcessState's Sys method. 319 | if exitErr, ok := err.(*exec.ExitError); ok { 320 | if waitStatus, ok := exitErr.Sys().(syscall.WaitStatus); ok { 321 | // Exit codes for diff are: 322 | // 0: no differences were found 323 | // 1: some differences were found 324 | // >1: trouble 325 | if waitStatus.Exited() && waitStatus.ExitStatus() == 1 { 326 | return true, nil 327 | } 328 | } 329 | } 330 | } 331 | 332 | return changes, err 333 | } 334 | -------------------------------------------------------------------------------- /retrodep/vendored.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "bytes" 20 | "io/ioutil" 21 | "os" 22 | "path/filepath" 23 | "strings" 24 | 25 | "github.com/Masterminds/semver" 26 | "github.com/pkg/errors" 27 | "golang.org/x/tools/go/vcs" 28 | ) 29 | 30 | func pathStartsWith(dir, prefix string) bool { 31 | return strings.HasPrefix(dir, prefix) && 32 | (len(dir) == len(prefix) || dir[len(prefix)] == filepath.Separator) 33 | } 34 | 35 | type vendoredSearch struct { 36 | // Path to the "vendor" directory 37 | vendor string 38 | 39 | // Path to last project identified 40 | lastdir string 41 | 42 | // Vendored packages, indexed by Root 43 | vendored map[string]*RepoPath 44 | } 45 | 46 | func (s *vendoredSearch) inLastDir(pth string) bool { 47 | return s.lastdir != "" && pathStartsWith(pth, s.lastdir) 48 | } 49 | 50 | func processVendoredSource(src *GoSource, search *vendoredSearch, pth string) error { 51 | // For .go source files, see which directory they are in 52 | rel, err := filepath.Rel(search.vendor, pth) 53 | if err != nil { 54 | return err 55 | } 56 | thisImport := filepath.ToSlash(filepath.Dir(rel)) 57 | repoPath, err := src.RepoPathForImportPath(thisImport) 58 | if err != nil { 59 | search.vendored[thisImport] = &RepoPath{RepoRoot: vcs.RepoRoot{Root: thisImport}, Err: err} 60 | return nil 61 | } 62 | 63 | // The project name is relative to the vendor dir 64 | search.vendored[repoPath.Root] = repoPath 65 | search.lastdir = filepath.Join(search.vendor, 66 | filepath.FromSlash(repoPath.Root)) 67 | return nil 68 | } 69 | 70 | // VendoredProjects return a map of project import names to information 71 | // about those projects, including which version control system they use. 72 | func (src GoSource) VendoredProjects() (map[string]*RepoPath, error) { 73 | search := vendoredSearch{ 74 | vendor: src.Vendor(), 75 | vendored: make(map[string]*RepoPath), 76 | } 77 | walkfn := func(pth string, info os.FileInfo, err error) error { 78 | if err != nil { 79 | // Stop on error 80 | return err 81 | } 82 | 83 | // Ignore paths within the last project we identified 84 | if search.inLastDir(pth) { 85 | return nil 86 | } 87 | 88 | // Ignore anything except Go source 89 | if !info.Mode().IsRegular() || !strings.HasSuffix(pth, ".go") { 90 | return nil 91 | } 92 | 93 | // Identify the project 94 | return processVendoredSource(&src, &search, pth) 95 | } 96 | 97 | if _, err := os.Stat(src.Path); err != nil { 98 | return nil, err 99 | } 100 | 101 | _, err := os.Stat(search.vendor) 102 | if err != nil { 103 | if !os.IsNotExist(err) { 104 | return nil, err 105 | } 106 | } else { 107 | err = filepath.Walk(search.vendor, walkfn) 108 | if err != nil { 109 | return nil, err 110 | } 111 | } 112 | 113 | return search.vendored, nil 114 | } 115 | 116 | // updateHashesAfterStrip syncs the tree to tag or revision ref and 117 | // recalculates file hashes for the provided paths based on stripping 118 | // import comments (in the same way as godep). The boolean return 119 | // value indicates whether any of the supplied hashes were modified as 120 | // a result. 121 | func updateHashesAfterStrip(hashes FileHashes, wt WorkingTree, ref string, paths []string) (bool, error) { 122 | // Update working tree to match the ref 123 | err := wt.RevSync(ref) 124 | if err != nil { 125 | return false, errors.Wrapf(err, "RevSync to %s", ref) 126 | } 127 | 128 | anyChanged := false 129 | for _, path := range paths { 130 | w := bytes.NewBuffer(nil) 131 | changed, err := wt.StripImportComment(path, w) 132 | if err != nil { 133 | return false, err 134 | } 135 | if !changed { 136 | continue 137 | } 138 | 139 | // Write the altered content out to a file 140 | f, err := ioutil.TempFile("", "retrodep-strip.") 141 | if err != nil { 142 | return anyChanged, errors.Wrap(err, "updating hash") 143 | } 144 | 145 | // Remove the new file after we've hashed it 146 | defer os.Remove(f.Name()) 147 | 148 | // Write to the file and close it, checking for errors 149 | _, err = w.WriteTo(f) 150 | if err != nil { 151 | f.Close() // ignore any secondary error 152 | return anyChanged, errors.Wrap(err, "updating hash") 153 | } 154 | 155 | if err = f.Close(); err != nil { 156 | return anyChanged, errors.Wrap(err, "updating hash") 157 | } 158 | 159 | // Re-hash the altered file 160 | h, err := wt.Hash(path, f.Name()) 161 | if err != nil { 162 | return anyChanged, err 163 | } 164 | hashes[path] = h 165 | anyChanged = true 166 | 167 | } 168 | 169 | return anyChanged, nil 170 | } 171 | 172 | func matchFromRefs(strip bool, hashes FileHashes, wt WorkingTree, subPath string, refs []string) ([]string, error) { 173 | var paths []string 174 | if strip { 175 | for path := range hashes { 176 | paths = append(paths, filepath.Join(subPath, path)) 177 | } 178 | } 179 | 180 | matchFromRef := func(th FileHashes, ref string) (bool, error) { 181 | if hashes.IsSubsetOf(th) { 182 | return true, nil 183 | } 184 | 185 | if !strip { 186 | return false, nil 187 | } 188 | 189 | for _, path := range paths { 190 | if _, ok := th[path]; !ok { 191 | // File missing from revision 192 | return false, nil 193 | } 194 | } 195 | 196 | changed, err := updateHashesAfterStrip(th, wt, ref, paths) 197 | if err != nil { 198 | return false, err 199 | } 200 | 201 | return changed && hashes.IsSubsetOf(th), nil 202 | } 203 | 204 | matches := make([]string, 0) 205 | for _, ref := range refs { 206 | log.Debugf("%s: trying match", ref) 207 | refHashes, err := wt.FileHashesFromRef(ref, subPath) 208 | if err != nil { 209 | if err == ErrorInvalidRef { 210 | continue 211 | } 212 | return nil, err 213 | } 214 | ok, err := matchFromRef(refHashes, ref) 215 | if err != nil { 216 | return nil, err 217 | } 218 | if ok { 219 | matches = append(matches, ref) 220 | } else if len(matches) > 0 { 221 | // This is the end of a matching run of refs 222 | break 223 | } 224 | } 225 | 226 | if len(matches) == 0 { 227 | return nil, ErrorVersionNotFound 228 | } 229 | 230 | return matches, nil 231 | } 232 | 233 | // Reference describes the origin of a vendored project. 234 | type Reference struct { 235 | // TopPkg is the name of the top-level package this package is 236 | // vendored into, or "" if Pkg is the top-level package. 237 | TopPkg string 238 | 239 | // TopVer is the Ver string (see below) for the TopPkg, if 240 | // defined. 241 | TopVer string 242 | 243 | // Pkg is the name of the package this Reference relates to. 244 | Pkg string 245 | 246 | // Repo is the URL for the repository holding the source code. 247 | Repo string 248 | 249 | // Tag is the semver tag within the upstream repository which 250 | // corresponds exactly to the vendored copy of the project. If 251 | // no tag corresponds Tag is "". 252 | Tag string 253 | 254 | // Rev is the upstream revision from which the vendored 255 | // copy was taken. If this is not known Rev is "". 256 | Rev string 257 | 258 | // Ver is the semantic version or pseudo-version for the 259 | // commit named in Reference. This is Tag if Tag is not "". 260 | Ver string 261 | } 262 | 263 | // chooseBestTag takes a sorted list of tags and returns the oldest 264 | // semver tag which is not a prerelease, or else the oldest tag. 265 | func chooseBestTag(tags []string) string { 266 | for i := len(tags) - 1; i >= 0; i-- { 267 | tag := tags[i] 268 | v, err := semver.NewVersion(tag) 269 | if err != nil { 270 | continue 271 | } 272 | if v.Prerelease() == "" { 273 | log.Debugf("best from %v: %v (no prerelease)", tags, tag) 274 | return tag 275 | } 276 | } 277 | 278 | tag := tags[len(tags)-1] 279 | log.Debugf("best from %v: %v (earliest)", tags, tag) 280 | return tag 281 | } 282 | 283 | func (src GoSource) hashLocalFiles(hasher Hasher, project *RepoPath, dir string) (FileHashes, error) { 284 | // Make a local copy of src.excludes we can add keys to 285 | excludes := make(map[string]struct{}) 286 | for key := range src.excludes { 287 | excludes[key] = struct{}{} 288 | } 289 | 290 | // Ignore vendor directory 291 | excludes[filepath.Join(dir, "vendor")] = struct{}{} 292 | 293 | // Work out the sub-directory within the repository root to 294 | // use for comparison. 295 | subPath := project.SubPath 296 | projDir := filepath.Join(project.Root, subPath) 297 | log.Debugf("describing %s compared to %s", dir, projDir) 298 | 299 | // Compute the hashes of the local files 300 | hashes, err := NewFileHashes(hasher, dir, excludes) 301 | if err != nil { 302 | return nil, err 303 | } 304 | 305 | for path := range hashes { 306 | // Ignore dot files (e.g. .git) 307 | if strings.HasPrefix(path, ".") { 308 | delete(hashes, path) 309 | } 310 | } 311 | 312 | if len(hashes) == 0 { 313 | return nil, ErrorNoFiles 314 | } 315 | 316 | return hashes, nil 317 | } 318 | 319 | // DescribeProject attempts to identify the tag in the version control 320 | // system which corresponds to the project, available in the working 321 | // tree wt, based on comparison with files in dir. Vendored files and 322 | // files whose names begin with "." are ignored. If top is not nil, 323 | // it should be a Reference to the top-level package this project is 324 | // vendored into. 325 | func (src GoSource) DescribeProject( 326 | project *RepoPath, 327 | wt WorkingTree, 328 | dir string, 329 | top *Reference, 330 | ) (*Reference, error) { 331 | hashes, err := src.hashLocalFiles(wt, project, dir) 332 | if err != nil { 333 | return nil, err 334 | } 335 | 336 | // Work out the sub-directory within the repository root to 337 | // use for comparison. 338 | subPath := project.SubPath 339 | projDir := filepath.Join(project.Root, subPath) 340 | log.Debugf("describing %s compared to %s", dir, projDir) 341 | 342 | // If godep is in use, strip import comments from the 343 | // project's vendored files (but not files from the top-level 344 | // project). 345 | strip := src.usesGodep && dir != src.Path 346 | 347 | var toppkg, topver string 348 | if top != nil { 349 | toppkg = top.Pkg 350 | topver = top.Ver 351 | } 352 | 353 | ref := &Reference{ 354 | TopPkg: toppkg, 355 | TopVer: topver, 356 | Pkg: project.Root, 357 | Repo: project.Repo, 358 | } 359 | 360 | // First try to match against a specific version, if specified 361 | if project.Version != "" { 362 | matches, err := matchFromRefs(strip, hashes, wt, 363 | subPath, []string{project.Version}) 364 | switch err { 365 | case nil: 366 | // Found a match 367 | match := matches[0] 368 | log.Debugf("Found match for %q which matches dependency management version", match) 369 | ver, err := PseudoVersion(wt, match) 370 | if err != nil { 371 | return nil, err 372 | } 373 | 374 | ref.Rev = match 375 | ref.Ver = ver 376 | return ref, nil 377 | case ErrorVersionNotFound: 378 | // No match, carry on 379 | default: 380 | // Some other error, fail 381 | return nil, err 382 | } 383 | } 384 | 385 | // Second try matching against tags for semantic versions 386 | tags, err := wt.VersionTags() 387 | if err != nil { 388 | return ref, err 389 | } 390 | 391 | matches, err := matchFromRefs(strip, hashes, wt, subPath, tags) 392 | switch err { 393 | case nil: 394 | // Found a match 395 | match := chooseBestTag(matches) 396 | rev, err := wt.RevisionFromTag(match) 397 | if err != nil { 398 | return nil, err 399 | } 400 | 401 | ref.Tag = match 402 | ref.Rev = rev 403 | ref.Ver = match 404 | return ref, nil 405 | case ErrorVersionNotFound: 406 | // No match, carry on 407 | default: 408 | // Some other error, fail 409 | return nil, err 410 | } 411 | 412 | // Third try each revision 413 | revs, err := wt.Revisions() 414 | if err != nil { 415 | return ref, err 416 | } 417 | 418 | matches, err = matchFromRefs(strip, hashes, wt, subPath, revs) 419 | if err != nil { 420 | return ref, err 421 | } 422 | 423 | // Use newest matching revision 424 | rev := matches[0] 425 | ver, err := PseudoVersion(wt, rev) 426 | if err != nil { 427 | return ref, err 428 | } 429 | 430 | ref.Rev = rev 431 | ref.Ver = ver 432 | return ref, nil 433 | } 434 | 435 | // DescribeVendoredProject attempts to identify the tag in the version 436 | // control system which corresponds to the vendored copy of the 437 | // project. 438 | func (src GoSource) DescribeVendoredProject( 439 | project *RepoPath, 440 | wt WorkingTree, 441 | top *Reference, 442 | ) (*Reference, error) { 443 | projRootImportPath := filepath.FromSlash(project.Root) 444 | projDir := filepath.Join(src.Vendor(), projRootImportPath) 445 | ref, err := src.DescribeProject(project, wt, projDir, top) 446 | return ref, err 447 | } 448 | -------------------------------------------------------------------------------- /retrodep/gosource.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018, 2019 Tim Waugh 2 | // 3 | // This program is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // This program is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU General Public License 14 | // along with this program. If not, see . 15 | 16 | package retrodep 17 | 18 | import ( 19 | "encoding/json" 20 | "fmt" 21 | "go/build" 22 | "io" 23 | "os" 24 | "path" 25 | "path/filepath" 26 | "strings" 27 | 28 | "github.com/op/go-logging" 29 | "github.com/pkg/errors" 30 | "golang.org/x/tools/go/vcs" 31 | 32 | "github.com/release-engineering/retrodep/v2/retrodep/glide" 33 | ) 34 | 35 | var vcsRepoRootForImportPath = vcs.RepoRootForImportPath 36 | 37 | // RepoPath is a vcs.RepoRoot along with the sub-path within the 38 | // repository, and the version. 39 | type RepoPath struct { 40 | vcs.RepoRoot 41 | 42 | // SubPath is the top-level filepath relative to the root of 43 | // the repository, or "" if they are the same. 44 | SubPath string 45 | 46 | Version string 47 | 48 | // Error encountered when finding repo path. 49 | Err error 50 | } 51 | 52 | var log = logging.MustGetLogger("retrodep") 53 | var errorNoImportPathComment = errors.New("no import path comment") 54 | 55 | // GoSource represents a filesystem tree containing Go source code. 56 | type GoSource struct { 57 | // Path is the filepath to the top-level package 58 | Path string 59 | 60 | // SubPath is the top-level filepath relative to the root of 61 | // the repository, or "" if they are the same. 62 | SubPath string 63 | 64 | // Package is the import path for the top-level package 65 | Package string 66 | 67 | // repoPaths maps apparent import paths to actual repositories 68 | repoPaths map[string]*RepoPath 69 | 70 | // excludes is a map of paths to ignore in this project 71 | excludes map[string]struct{} 72 | 73 | // usesGodep is true if Godeps/Godeps.json is present 74 | usesGodep bool 75 | } 76 | 77 | // FindExcludes returns a slice of paths which match the provided 78 | // globs. 79 | func FindExcludes(path string, globs []string) ([]string, error) { 80 | excludes := make([]string, 0) 81 | for _, glob := range globs { 82 | matches, err := filepath.Glob(filepath.Join(path, glob)) 83 | if err != nil { 84 | return nil, err 85 | } 86 | for _, match := range matches { 87 | excludes = append(excludes, match) 88 | } 89 | } 90 | return excludes, nil 91 | } 92 | 93 | // FindGoSources looks for top-level projects at path. If path is itself 94 | // a top-level project, the returned slice contains a single *GoSource 95 | // for that project; otherwise immediate sub-directories are tested. 96 | // Files matching globs in excludeGlobs will not be considered when 97 | // matching against upstream repositories. 98 | func FindGoSources(path string, excludeGlobs []string) ([]*GoSource, error) { 99 | // Try at the top-level. 100 | excludes, err := FindExcludes(path, excludeGlobs) 101 | if err != nil { 102 | return nil, err 103 | } 104 | src, terr := NewGoSource(path, excludes) 105 | if terr == nil { 106 | log.Debugf("found project at top-level: %s", path) 107 | return []*GoSource{src}, nil 108 | } 109 | 110 | // Convert the exclusions list to absolute paths and make a 111 | // map for fast look-up. 112 | excl := make(map[string]struct{}) 113 | for _, e := range excludes { 114 | a, err := filepath.Abs(e) 115 | if err != nil { 116 | return nil, err 117 | } 118 | excl[a] = struct{}{} 119 | } 120 | 121 | // Work out the absolute path we were given, for constructing 122 | // keys to look up in excl 123 | abs, err := filepath.Abs(path) 124 | if err != nil { 125 | return nil, errors.Wrapf(err, "Abs(%q)", path) 126 | } 127 | 128 | // Look in sub-directories. 129 | subDirStart := len(abs) + 1 130 | srcs := make([]*GoSource, 0) 131 | search := func(p string, info os.FileInfo, err error) error { 132 | if err != nil { 133 | return err 134 | } 135 | 136 | // Ignore the top-level directory itself. 137 | if p == abs { 138 | return nil 139 | } 140 | 141 | // Only consider directories. 142 | if !info.IsDir() { 143 | return nil 144 | } 145 | 146 | // We only want to consider sub-directories one level 147 | // down from the top-level. 148 | if strings.ContainsRune(p[subDirStart:], filepath.Separator) { 149 | return filepath.SkipDir 150 | } 151 | 152 | // Check if this is excluded from consideration 153 | if _, ok := excl[p]; ok { 154 | return filepath.SkipDir 155 | } 156 | 157 | r := filepath.Join(path, p[subDirStart:]) 158 | src, err := NewGoSource(r, excludes) 159 | if err != nil { 160 | if _, ok := err.(*build.NoGoError); ok { 161 | return nil 162 | } 163 | return err 164 | } 165 | 166 | err = src.SetSubPath(path) 167 | if err != nil { 168 | return err 169 | } 170 | 171 | srcs = append(srcs, src) 172 | log.Debugf("found project in subdir: %s", r) 173 | return nil 174 | } 175 | 176 | err = filepath.Walk(abs, search) 177 | if err != nil { 178 | return nil, err 179 | } 180 | 181 | if len(srcs) == 0 { 182 | // Return the original error from the top-level check. 183 | if _, ok := terr.(*build.NoGoError); ok { 184 | return nil, ErrorNoGo 185 | } 186 | 187 | return nil, terr 188 | } 189 | 190 | return srcs, nil 191 | } 192 | 193 | // NewGoSource returns a *GoSource for the given path path. The paths 194 | // in excludes will not be considered when matching against the 195 | // upstream repository. 196 | func NewGoSource(path string, excludes []string) (*GoSource, error) { 197 | // There has to be either: 198 | // - a 'vendor' subdirectory, or 199 | // - some '*.go' files with Go code in 200 | // Otherwise there is nothing for us to do. 201 | var vendorExists bool 202 | st, err := os.Stat(filepath.Join(path, "vendor")) 203 | if err == nil { 204 | vendorExists = st.IsDir() 205 | } 206 | switch { 207 | case vendorExists: 208 | // There is a vendor directory. Nothing else to check. 209 | case err == nil || os.IsNotExist(err): 210 | // No vendor directory, check for Go source. 211 | _, err := build.ImportDir(path, build.ImportComment) 212 | if err != nil { 213 | return nil, err 214 | } 215 | default: 216 | // Some other failure. 217 | return nil, err 218 | } 219 | 220 | excl := make(map[string]struct{}) 221 | for _, e := range excludes { 222 | excl[e] = struct{}{} 223 | } 224 | 225 | src := &GoSource{ 226 | Path: path, 227 | excludes: excl, 228 | } 229 | 230 | // Always read Godeps.json because we need to know whether 231 | // godep is in use (if so, files are modified when vendored). 232 | err = loadGodepsConf(src) 233 | if err != nil { 234 | return nil, err 235 | } 236 | 237 | // Always read glide.yaml because we need to know if there are 238 | // replacement repositories. 239 | ok, err := loadGlideConf(src) 240 | if err != nil { 241 | return nil, err 242 | } 243 | 244 | if !ok && src.Package == "" { 245 | if importPath, err := findImportComment(src); err == nil { 246 | src.Package = importPath 247 | } else if importPath, ok := importPathFromFilepath(path); ok { 248 | src.Package = importPath 249 | } 250 | } 251 | 252 | return src, nil 253 | } 254 | 255 | // loadGodepsConf parses Godeps/Godeps.json to extract the package 256 | // name. 257 | func loadGodepsConf(src *GoSource) error { 258 | type godepsConf struct { 259 | ImportPath string 260 | } 261 | conf := filepath.Join(src.Path, "Godeps", "Godeps.json") 262 | if _, skip := src.excludes[conf]; skip { 263 | return nil 264 | } 265 | f, err := os.Open(conf) 266 | if err != nil { 267 | if os.IsNotExist(err) { 268 | return nil 269 | } 270 | return err 271 | } 272 | defer f.Close() 273 | 274 | src.usesGodep = true 275 | dec := json.NewDecoder(f) 276 | var godeps godepsConf 277 | err = dec.Decode(&godeps) 278 | if err != nil { 279 | return err 280 | } 281 | 282 | src.Package = godeps.ImportPath 283 | log.Debugf("import path found from Godeps/Godeps.json: %s", src.Package) 284 | return nil 285 | } 286 | 287 | // loadGlideConf parses glide.yaml to extract the package name and the 288 | // import path repository replacements. It returns true if it parsed 289 | // successfully. 290 | func loadGlideConf(src *GoSource) (bool, error) { 291 | conf := filepath.Join(src.Path, "glide.yaml") 292 | if _, skip := src.excludes[conf]; skip { 293 | return false, nil 294 | } 295 | 296 | glide, err := glide.LoadGlide(src.Path) 297 | if err != nil { 298 | if os.IsNotExist(err) { 299 | return false, nil 300 | } 301 | return false, errors.Wrapf(err, "decoding %s", conf) 302 | } 303 | 304 | src.Package = glide.Package 305 | log.Debugf("import path found from glide.yaml: %s", src.Package) 306 | 307 | // if there is no vendor folder, the dependencies are flattened 308 | _, err = os.Stat(filepath.Join(src.Path, "vendor")) 309 | if os.IsNotExist(err) { 310 | return true, nil 311 | } 312 | if err != nil { 313 | return false, errors.Wrapf(err, "stat 'vendor' for %s", conf) 314 | } 315 | 316 | repoPaths := make(map[string]*RepoPath) 317 | for _, imp := range glide.Imports { 318 | theVcs := vcs.ByCmd(vcsGit) // default to git 319 | if imp.Repo == "" { 320 | root, err := vcs.RepoRootForImportPath(imp.Name, false) 321 | if err != nil { 322 | log.Infof("Skipping %v, could not determine repo root: %v", imp.Name, err) 323 | continue 324 | } 325 | imp.Repo = root.Repo 326 | theVcs = root.VCS 327 | } 328 | 329 | repoPaths[imp.Name] = &RepoPath{ 330 | RepoRoot: vcs.RepoRoot{ 331 | VCS: theVcs, 332 | Repo: imp.Repo, 333 | Root: imp.Name, 334 | }, 335 | Version: imp.Version, 336 | } 337 | } 338 | 339 | src.repoPaths = repoPaths 340 | return true, nil 341 | } 342 | 343 | // importPathFromFilepath attempts to use the project directory path to 344 | // infer its import path. 345 | func importPathFromFilepath(path string) (string, bool) { 346 | absPath, err := filepath.Abs(path) 347 | if err != nil { 348 | return "", false 349 | } 350 | 351 | // Skip leading '/' 352 | path = absPath[1:] 353 | components := strings.Split(path, string(filepath.Separator)) 354 | if len(components) < 2 { 355 | return "", false 356 | } 357 | 358 | for i := len(components) - 2; i >= 0; i-- { 359 | // Avoid false positives like: 360 | // github.com/release-engineering/retrodep/retrodep/testdata/gosource 361 | switch components[i] { 362 | case "testdata", "vendor": 363 | return "", false 364 | } 365 | 366 | if strings.Index(components[i], ".") == -1 { 367 | // Not a hostname 368 | continue 369 | } 370 | 371 | p := strings.Join(components[i:len(components)], "/") 372 | _, err := vcs.RepoRootForImportPath(p, false) 373 | if err == nil { 374 | return p, true 375 | } 376 | } 377 | 378 | return "", false 379 | } 380 | 381 | func findImportComment(src *GoSource) (string, error) { 382 | // Define the error we'll use to end the filepath.Walk method early. 383 | errFound := errors.New("found") 384 | 385 | // importPath holds the import path we've discovered. It will 386 | // be updated by the 'search' closure, below. 387 | var importPath string 388 | 389 | search := func(path string, info os.FileInfo, err error) error { 390 | if _, skip := src.excludes[path]; skip { 391 | if info.IsDir() { 392 | return filepath.SkipDir 393 | } 394 | return nil 395 | } 396 | if err != nil { 397 | return err 398 | } 399 | if !info.IsDir() { 400 | return nil 401 | } 402 | if info.Name() != "." && 403 | strings.HasPrefix(info.Name(), ".") { 404 | return filepath.SkipDir 405 | } 406 | switch info.Name() { 407 | // Skip these special directories since "vendor" and 408 | // "_override" contain local copies of dependencies 409 | // and "testdata" includes data files only used for 410 | // testing that can be safely ignored. 411 | case "vendor", "testdata", "_override": 412 | return filepath.SkipDir 413 | } 414 | 415 | pkg, err := build.ImportDir(path, build.ImportComment) 416 | if err != nil { 417 | if _, ok := err.(*build.NoGoError); ok { 418 | return nil 419 | } 420 | return err 421 | } 422 | if pkg.ImportComment != "" { 423 | // Work backwards to find the top-level import path 424 | rel, err := filepath.Rel(src.Path, path) 425 | if err != nil { 426 | return errors.Wrapf(err, "Rel(%q, %q)", src.Path, path) 427 | } 428 | 429 | sub := filepath.ToSlash(rel) 430 | p := pkg.ImportComment 431 | switch { 432 | case rel == ".": 433 | // This is in a top-level file so use 434 | // the import comment as-is. 435 | importPath = p 436 | case !strings.HasSuffix(p, sub): 437 | // Subdirectory doesn't match the end 438 | // of the import comment. 439 | log.Debugf("ignoring import path in %s: %s", 440 | sub, p) 441 | return nil 442 | default: 443 | // If we found "import/path/sub" from parsing 444 | // in "sub", find "import/path" by shrinking 445 | // the slice from the end by the length of 446 | // "sub" and by the additional separator. 447 | importPath = p[:len(p)-1-len(sub)] 448 | } 449 | 450 | log.Debugf("found import path from import comment: %s", 451 | importPath) 452 | return errFound 453 | } 454 | return nil 455 | } 456 | 457 | err := filepath.Walk(src.Path, search) 458 | if err == errFound { 459 | err = nil 460 | } else if err == nil { 461 | err = errorNoImportPathComment 462 | } 463 | return importPath, err 464 | } 465 | 466 | // SetSubPath updates the GoSource.SubPath string to be relative to 467 | // the given root. 468 | func (src *GoSource) SetSubPath(root string) error { 469 | rel, err := filepath.Rel(root, src.Path) 470 | if err != nil { 471 | return errors.Wrapf(err, "Rel(%q, %q)", root, src.Path) 472 | } 473 | src.SubPath = rel 474 | return nil 475 | } 476 | 477 | // Vendor returns the path to the vendored source code. 478 | func (src GoSource) Vendor() string { 479 | return filepath.Join(src.Path, "vendor") 480 | } 481 | 482 | // Project returns information about the project's repository, as well 483 | // as the project's path within the repository, given its import 484 | // path. If importPath is "" it is deduced from import comments, if 485 | // available. 486 | func (src GoSource) Project(importPath string) (*RepoPath, error) { 487 | if importPath == "" { 488 | importPath = src.Package 489 | if importPath == "" { 490 | return nil, ErrorNeedImportPath 491 | } 492 | } 493 | 494 | repoRoot, err := vcsRepoRootForImportPath(importPath, false) 495 | if err != nil { 496 | return &RepoPath{ 497 | RepoRoot: vcs.RepoRoot{Root: importPath}, 498 | Err: err, 499 | }, nil 500 | } 501 | 502 | // Work out root path 503 | r := repoRoot.Root 504 | var subPath string 505 | switch { 506 | case importPath == r: 507 | // Sub path is "" 508 | case !strings.HasPrefix(importPath, r) || importPath[len(r)] != '/': 509 | return nil, fmt.Errorf("expected prefix of %s: %s", importPath, r) 510 | default: 511 | subPath = importPath[len(r)+1:] 512 | } 513 | 514 | return &RepoPath{ 515 | RepoRoot: *repoRoot, 516 | SubPath: subPath, 517 | }, err 518 | } 519 | 520 | // RepoPathForImportPath takes an import path and returns a *RepoPath 521 | // for it, based on possible replacements within the Go source 522 | // configuration. 523 | func (src GoSource) RepoPathForImportPath(importPath string) (*RepoPath, error) { 524 | // First look up replacements 525 | pth := importPath 526 | for { 527 | repl, ok := src.repoPaths[pth] 528 | if ok { 529 | // Found a replacement repo 530 | return repl, nil 531 | } 532 | 533 | // Try shorter import path 534 | pth = path.Dir(pth) 535 | if len(pth) == 1 { 536 | break 537 | } 538 | } 539 | 540 | // No replacement found, use the import pth as-is 541 | r, err := vcs.RepoRootForImportPath(importPath, false) 542 | if err != nil { 543 | u := strings.Index(importPath, "_") 544 | if u == -1 { 545 | return nil, err 546 | } 547 | // gopkg.in gives bad responses for paths like 548 | // gopkg.in/foo/bar.v2/_examples/chat1 549 | // because of the underscore. Remove it and try again. 550 | importPath = path.Dir(importPath[:u]) 551 | r2, err2 := vcs.RepoRootForImportPath(importPath, false) 552 | if err2 != nil { 553 | return nil, err // Returning the initial error is intentional 554 | } 555 | return &RepoPath{RepoRoot: *r2}, nil 556 | } 557 | return &RepoPath{RepoRoot: *r}, nil 558 | } 559 | 560 | // Diff writes (to out) the differences between the Go source code at 561 | // dir and the repository at revision ref, ignoring files which are 562 | // only present in the repository. It returns true if changes were 563 | // found and false if not. 564 | func (src GoSource) Diff(project *RepoPath, wt WorkingTree, out io.Writer, dir, ref string) (bool, error) { 565 | // Hash the local files. 566 | hashes, err := src.hashLocalFiles(wt, project, dir) 567 | if err != nil { 568 | return false, err 569 | } 570 | 571 | // Work out the sub-directory within the repository root to 572 | // use for comparison. 573 | subPath := project.SubPath 574 | projDir := filepath.Join(project.Root, subPath) 575 | log.Debugf("describing %s compared to %s", dir, projDir) 576 | 577 | // If godep is in use, strip import comments from the 578 | // project's vendored files (but not files from the top-level 579 | // project). 580 | strip := src.usesGodep && dir != src.Path 581 | 582 | // Sync the files in the working tree to the requested ref, 583 | // ready to diff them. 584 | err = wt.RevSync(ref) 585 | if err != nil { 586 | return false, err 587 | } 588 | 589 | refHashes, err := wt.FileHashesFromRef(ref, subPath) 590 | if err != nil { 591 | return false, err 592 | } 593 | 594 | if strip { 595 | // Update the working tree files corresponding to the 596 | // local files. 597 | var paths []string 598 | for path := range hashes { 599 | paths = append(paths, filepath.Join(subPath, path)) 600 | } 601 | 602 | _, err := updateHashesAfterStrip(hashes, wt, ref, paths) 603 | if err != nil { 604 | return false, err 605 | } 606 | } 607 | 608 | // For each file which differs, write the "diff -u" output. 609 | // For files added compared to upstream, write the "diff -u" 610 | // output compared to /dev/null. 611 | changes := false 612 | for _, mismatch := range hashes.Mismatches(refHashes, false) { 613 | var refFile string 614 | 615 | // Does the file exist in the working tree? 616 | if _, ok := refHashes[mismatch]; ok { 617 | refFile = filepath.Join(subPath, mismatch) 618 | } 619 | 620 | c, err := wt.Diff(out, refFile, filepath.Join(dir, mismatch)) 621 | if err != nil { 622 | return changes, err 623 | } 624 | 625 | changes = changes || c 626 | } 627 | return changes, nil 628 | } 629 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------