├── LICENSE ├── README.md ├── copy.go ├── editors └── emacs.el ├── godep.go ├── main.go ├── pins.go ├── purge.go ├── wgo-exec ├── README.md └── main.go ├── workspaces.go └── workspaces └── workspaces.go /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # wgo: managed workspaces on top of the go tool 2 | 3 | ## Overview 4 | The wgo tool is a small wrapper around the go tool. It adds the concept of a workspace, in addition to that of GOPATH, and several new commands to manage that workspace. 5 | 6 | 7 | ### How is this like... 8 | 9 | #### godep 10 | wgo is not at all like https://github.com/tools/godep (see "Philosophy", below). However, the `wgo save --godeps` command (see "wgo save", below) makes it easy to migrate from godep to wgo. 11 | 12 | #### gb 13 | wgo is very much like https://github.com/constabulary/gb except for some key details. 14 | - gb reimplements all of the build mechanics, where wgo uses the existing go tool. 15 | - gb works only from the root of the workspace by recognizing a "src" directory, where wgo adds an additional "W/.gocfg" directory and will search directory parents to find the workspace (like git or mercurial do with ".git" or ".hg" directories). As a result, gb can use wgo workspaces, but not the other way around without first running `wgo init` in the workspace root. 16 | - wgo has the save/restore functionality built in, where gb can potentially include them as plugins. 17 | - Both wgo and gb make it easy for you to create a single workspace that has everything you need for your project, and therefore make it easy to put your entire project in version control in a way that is easy for others to access. 18 | 19 | 20 | ### Goals 21 | - Ease unnecessary confusion around how to handle the GOPATH environment variable, especially for new gophers. 22 | - Provide a vendoring approach to dependency management for open source Go programs. 23 | - Eventually be merged into the go tool itself (ha ha). 24 | 25 | 26 | #### Philosophy? 27 | `go get` is not a tool to manage dependencies, it is a tool to acquire them. So, trying to cram dependency management underneath `go get` is a fundamental mistake and will only make for awkward source repos and usage. 28 | 29 | The approach used by wgo is to go *on top* of the go tool (and `go get`). It manages your entire workspace, and uses the go commands to operate on your workspace. 30 | 31 | As a result, github repositories that are made to work with `go get` do not work as wgo workspaces. This incongruency is intentional: `go get` fetches a single piece of your project, while wgo manages the whole thing. 32 | 33 | The wgo tool also uses a Go-agnostic tool, vendor (github.com/skelterjohn/vfu), to manage versions of dependencies. There is no reason to restrict vendoring goodness to Go projects. 34 | 35 | #### Typical use 36 | ``` 37 | $ mkdir myproject 38 | $ cd myproject 39 | $ wgo init 40 | $ wgo get github.com/someone/dep 41 | $ ls -a 42 | .gocfg src vendor 43 | $ mkdir src/myproj 44 | $ emacs src/myproj/main.go 45 | ... import "github.com/someone/dep" 46 | $ wgo install myproj 47 | $ ./bin/myproj 48 | it works! 49 | $ git init 50 | $ wgo save > .gitignore 51 | $ git add .gocfg .gitignore src/myproj 52 | $ git remote add origin https://foo.git 53 | $ git push origin 54 | ``` 55 | 56 | And later... 57 | 58 | ``` 59 | $ git clone https://foo.git 60 | $ cd foo 61 | $ wgo restore 62 | vendor/src/github.com/someone/dep 63 | $ ls -a 64 | .gocfg src vendor 65 | $ wgo install myproj 66 | $ ./bin/myproj 67 | it works! 68 | ``` 69 | 70 | 71 | #### Take it for a spin 72 | Repeat after me: 73 | 74 | ``` 75 | $ git clone https://github.com/skelterjohn/wgo-example-w 76 | Cloning into 'wgo-example-w'... 77 | remote: Counting objects: 12, done. 78 | remote: Compressing objects: 100% (7/7), done. 79 | remote: Total 12 (delta 0), reused 9 (delta 0), pack-reused 0 80 | Receiving objects: 100% (12/12), done. 81 | $ cd wgo-example-w/ 82 | wgo-example-w $ wgo restore 83 | vendor/src/github.com/skelterjohn/wgo-example-dep 84 | wgo-example-w $ wgo install prog 85 | wgo-example-w $ ./bin/prog 86 | bar 87 | ``` 88 | 89 | ### How it works 90 | Workspaces and new subcommands. 91 | 92 | 93 | #### Workspaces 94 | A workspace is a directory that contains a directory ".gocfg" at its top level. Any wgo commands run with a working directory that is a subdirectory of the workspace (including the workspace itself) are said to be run from within that workspace. 95 | 96 | 97 | #### wgo foo 98 | When a wgo command is run from within a workspace, it runs the equivalent go command (by forwarding all arguments) with a modified environment: the GOPATH environment variable is prefixed with the workspace and any other gopaths listed in "W/.gocfg/gopaths". 99 | 100 | For `wgo get`, the GOPATH used will only be taken from "W/.gocfg/gopaths". For any other go tool command, the GOPATH will also have the value taken from wgo's environment. 101 | 102 | So, if "W/.gocfg" exists, running wgo from within that workspace is the same as running go with each of the directories listed in "W/.gocfg/gopaths" inserted into the beginning of GOPATH, in order. 103 | 104 | You can modify "W/.gocfg/gopaths" at any time to change the GOPATH priority. For instance, if you put third party dependencies in "W/vendor/src", and you want calls to `go get` to put new source in there, make sure "W/vendor" is the first line in "W/.gocfg/gopaths" (this is the default when you run `wgo init` with no additional arguments). 105 | 106 | 107 | #### wgo-exec 108 | If you install "github.com/skelterjohn/wgo/wgo-exec", the wgo-exec tool can be used to run arbitrary commands with GOPATH adjusted for the workspace. In a bash shell, running `wgo-exec foo bar` is equivalent to `GOPATH=$(wgo env GOPATH) foo bar`. 109 | 110 | The wgo-exec tool can be useful for situations where it is easier to change the command run than to change the environment for a command. 111 | 112 | 113 | #### .gocfg/vendor.json 114 | The ".gocfg/vendor.json" file maps import paths to repository revisions. It is written and used by the "github.com/skelterjohn/vfu/vend" package. The `vendor` tool can also make use if it, and can be installed by running `go get github.com/skelterjohn/vfu`. 115 | 116 | 117 | ## New commands 118 | There are several new commands introduced to help with management of workspaces. If one of these commands is the first argument to wgo, it will run special logic associated with that command. Otherwise, it will forward all arguments directly to the go tool. 119 | 120 | 121 | ### wgo init 122 | The init command will create a ".gocfg" directory in the current directory, and ".gocfg/gopaths" within it. And "src", just to make things clear. 123 | 124 | Extra arguments after `wgo init` will be extra directories listed in ".gocfg/gopaths". They must be relative paths, and will be interpreted as being relative to the root of the workspace. 125 | 126 | If you provide a flag `--vendor-gopath=DIR`, then "DIR" will be the first directory listed in ".gocfg/gopaths". Being listed first means that it will be where `go get` puts new packages, and where `wgo save` will use as a default location for packages currently outside of "W". 127 | 128 | 129 | ### wgo save 130 | The save subcommand will find all revision numbers for all dependencies currently used by any package in the workspace, and write them to ".gocfg/vendor.json". 131 | 132 | Since running `wgo save` will print out a list of paths, relative to W, where it will put repositories, it makes sense to put that output into ".gitignore", ".hgignore", or whatever. Eg, `W$ wgo save >> .gitignore` is a nice convenience to make sure the repos are not accidentally included in your workspace repository, if you choose to version it. 133 | 134 | Adding the `--godeps` flag after `wgo save` will cause wgo to collect revision pins from all "Godeps/Godeps.json" files it finds in the workspace, and bring them into ".gocfg/vendor.json". 135 | 136 | As a result, a way to transform a godep-managed package into a wgo workspace is to run 137 | 138 | ``` 139 | W$ wgo init 140 | W$ wgo get 141 | W$ wgo save --godeps 142 | W$ wgo restore 143 | ``` 144 | 145 | 146 | ### wgo restore 147 | The restore subcommand will update all repositories in "W/src" to the revision numbers specified in ".gocfg/vendor.json". 148 | 149 | 150 | ### wgo vendor 151 | The vendor subcommand will find all Go dependencies that are outside of the workspace and copy them into the workspace. Useful if you intend to completely vendor a workspace. 152 | 153 | 154 | ### wgo purge 155 | The purge subcommand lists and deletes (if you provide the `--confirm` flag) all directories that do not contain source imported by something outside of the directories being purged. By default, the first `GOPATH` is purged (and by default, that is the `vendor` dir). 156 | -------------------------------------------------------------------------------- /copy.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2015 Google Inc. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | // "fmt" 18 | "io" 19 | "os" 20 | "path/filepath" 21 | ) 22 | 23 | func copyDir(src, dst string) { 24 | walk := func(path string, info os.FileInfo, err error) error { 25 | if err != nil { 26 | return err 27 | } 28 | relPath, err := filepath.Rel(src, path) 29 | if err != nil { 30 | return err 31 | } 32 | dstPath := filepath.Join(dst, relPath) 33 | finfo, err := os.Stat(path) 34 | if err != nil { 35 | //fmt.Fprintf(os.Stderr, "%s: %v\n", path, err) 36 | return nil 37 | } 38 | if finfo.IsDir() { 39 | return os.MkdirAll(dstPath, finfo.Mode()) 40 | } 41 | return copyFile(finfo, path, dstPath) 42 | } 43 | filepath.Walk(src, walk) 44 | } 45 | 46 | func copyFile(finfo os.FileInfo, src, dst string) error { 47 | fin, err := os.Open(src) 48 | if err != nil { 49 | return err 50 | } 51 | defer fin.Close() 52 | 53 | fout, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, finfo.Mode()) 54 | if err != nil { 55 | return err 56 | } 57 | defer fout.Close() 58 | 59 | if _, err = io.Copy(fout, fin); err != nil { 60 | return err 61 | } 62 | if err = fout.Close(); err != nil { 63 | return err 64 | } 65 | return fin.Close() 66 | } 67 | -------------------------------------------------------------------------------- /editors/emacs.el: -------------------------------------------------------------------------------- 1 | ;; Experimental wgo support for EMACS. 2 | ;; Allows go-mode and other go tools to be able to handle the 3 | ;; GOPATH changes that wgo does when they shell out to go for stuff. 4 | ;; To use, add (load-file "/path/to/this/file.el") to your emacs config. 5 | 6 | (defun setup-go-mode-env () 7 | (make-local-variable 'process-environment) 8 | (let ((val (shell-command-to-string "wgo env GOPATH"))) 9 | (if (not (string= val "no workspace")) 10 | (setenv "GOPATH" val) 11 | ) 12 | ) 13 | ) 14 | 15 | (add-hook 'go-mode 'setup-go-mode-env) 16 | 17 | (defun her-apply-function (orig-fun name) 18 | (let ((res (funcall orig-fun name))) 19 | (if (or (string= name "*gocode*") (string= name "*compilation*")) 20 | (setup-go-mode-env) 21 | ) 22 | res)) 23 | 24 | (advice-add 'generate-new-buffer :around #'her-apply-function) 25 | -------------------------------------------------------------------------------- /godep.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2015 Google Inc. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "encoding/json" 18 | "fmt" 19 | "os" 20 | "path/filepath" 21 | "sort" 22 | "strings" 23 | 24 | "golang.org/x/tools/go/vcs" 25 | ) 26 | 27 | type Godeps struct { 28 | Deps []Dependency 29 | } 30 | 31 | type Dependency struct { 32 | ImportPath string 33 | Rev string 34 | } 35 | 36 | func (w *workspace) importGodeps() map[string]dirDep { 37 | dirGs := map[string]Godeps{} 38 | scanDir := func(path string, info os.FileInfo, err error) error { 39 | if !info.IsDir() { 40 | return nil 41 | } 42 | if g, err := loadGodepsConfig(path); err == nil { 43 | dirGs[path] = g 44 | } 45 | return nil 46 | } 47 | filepath.Walk(w.Root, scanDir) 48 | return w.mergeGodeps(dirGs) 49 | } 50 | 51 | func loadGodepsConfig(dir string) (Godeps, error) { 52 | var g Godeps 53 | 54 | configPath := filepath.Join(dir, "Godeps", "Godeps.json") 55 | fin, err := os.Open(configPath) 56 | if err != nil { 57 | return g, err 58 | } 59 | return g, json.NewDecoder(fin).Decode(&g) 60 | } 61 | 62 | type dirDep struct { 63 | srcDir string 64 | repo string 65 | rev string 66 | root string 67 | kind string 68 | } 69 | 70 | // mergeGodeps will get one master list of revs. 71 | func (w *workspace) mergeGodeps(dirGs map[string]Godeps) map[string]dirDep { 72 | roots := map[string]dirDep{} 73 | for dir, g := range dirGs { 74 | for _, dep := range g.Deps { 75 | repoRoot, err := vcs.RepoRootForImportPath(dep.ImportPath, false) 76 | if err != nil { 77 | fmt.Fprintf(os.Stderr, "for %q: %s\n", dep.ImportPath, err) 78 | continue 79 | } 80 | dd := dirDep{ 81 | srcDir: dir, 82 | rev: dep.Rev, 83 | repo: repoRoot.Repo, 84 | root: filepath.Join(w.vendorRootSrc(), repoRoot.Root), 85 | kind: repoRoot.VCS.Cmd, 86 | } 87 | if orig, ok := roots[repoRoot.Repo]; ok { 88 | if orig != dd { 89 | fmt.Fprintf(os.Stderr, "conflict for %q: godeps in %q and %q do not match\n", 90 | dd.repo, orig.srcDir, dd.srcDir) 91 | continue 92 | } 93 | } else { 94 | roots[repoRoot.Root] = dd 95 | } 96 | } 97 | } 98 | 99 | // clear out nested 100 | var rootDirs sort.StringSlice 101 | for _, dd := range roots { 102 | rootDirs = append(rootDirs, dd.root) 103 | } 104 | sort.Sort(rootDirs) 105 | 106 | var last string 107 | for _, r := range rootDirs { 108 | if last != "" && strings.HasPrefix(r, last) { 109 | delete(roots, r) 110 | fmt.Fprintf(os.Stderr, "ignoring %q which is managed in %q\n", r, last) 111 | } else { 112 | last = r + string(filepath.Separator) 113 | } 114 | } 115 | 116 | return roots 117 | } 118 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2015 Google Inc. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | /* 15 | The wgo tool is a small wrapper around the go tool. It adds the concept 16 | of a workspace, in addition to that of GOPATH, and several new commands 17 | to manage that workspace. 18 | */ 19 | package main 20 | 21 | import ( 22 | "fmt" 23 | "io/ioutil" 24 | "log" 25 | "os" 26 | "path/filepath" 27 | "strings" 28 | ) 29 | 30 | const ( 31 | ConfigDirName = ".gocfg" 32 | ) 33 | 34 | var Debug bool 35 | 36 | const getFlag = "--vendor-gopath" 37 | 38 | var usageMessage = fmt.Sprintf(`wgo is a tool for managing Go workspaces. 39 | 40 | usage: wgo init [%s=VENDOR_GOPATH] [ADDITIONAL_GOPATH+] 41 | wgo restore 42 | wgo save [--godeps] [PACKAGE+] 43 | wgo vendor [PACKAGE+] 44 | wgo purge [GOPATH+] 45 | 46 | wgo # run a go command with the workspace's gopaths 47 | `, getFlag) 48 | 49 | func usage() { 50 | fmt.Print(usageMessage) 51 | os.Exit(1) 52 | } 53 | 54 | func init() { 55 | log.SetFlags(0) 56 | Debug = os.Getenv("WGO_DEBUG") == "1" 57 | if !Debug { 58 | log.SetOutput(ioutil.Discard) 59 | } 60 | log.Println("debug mode on") 61 | } 62 | 63 | func orExit(err error) { 64 | if err == nil { 65 | return 66 | } 67 | fmt.Fprintf(os.Stderr, "%s\n", err) 68 | os.Exit(1) 69 | } 70 | 71 | func main() { 72 | if len(os.Args) == 1 { 73 | fmt.Println(usageMessage) 74 | shellOutToGo(os.Args) 75 | } 76 | var err error 77 | switch os.Args[1] { 78 | case "init": 79 | if err = initWgo(os.Args[2:]); err != nil { 80 | fmt.Fprintf(os.Stderr, "%s\n", err) 81 | } 82 | case "vendor": 83 | w, err := getCurrentWorkspace() 84 | orExit(err) 85 | vendor(w, os.Args[2:]) 86 | case "restore": 87 | if len(os.Args) != 2 { 88 | usage() 89 | } 90 | w, err := getCurrentWorkspace() 91 | orExit(err) 92 | restore(w) 93 | case "purge": 94 | w, err := getCurrentWorkspace() 95 | orExit(err) 96 | purge(w, os.Args[2:]) 97 | case "save": 98 | w, err := getCurrentWorkspace() 99 | orExit(err) 100 | save(w, os.Args[2:]) 101 | default: 102 | w, err := getCurrentWorkspace() 103 | if err == nil { 104 | w.shellOutToGo(os.Args) 105 | } else { 106 | shellOutToGo(os.Args) 107 | } 108 | } 109 | } 110 | 111 | func initWgo(args []string) error { 112 | for _, arg := range args { 113 | if arg != getFlag && strings.HasPrefix(arg, "-") { 114 | fmt.Fprintf(os.Stderr, "unrecognized flag: %s\n\n", arg) 115 | usage() 116 | } 117 | } 118 | 119 | wd, err := os.Getwd() 120 | if err != nil { 121 | return err 122 | } 123 | 124 | w, err := getCurrentWorkspace() 125 | if err == nil && (w.Root == wd && len(args) == 0) { 126 | return fmt.Errorf("%q is already a workspace", w.Root) 127 | } 128 | 129 | fi, err := os.Stat(wd) 130 | if err != nil { 131 | return err 132 | } 133 | 134 | if err := os.MkdirAll(filepath.Join(wd, ConfigDirName), fi.Mode()); err != nil { 135 | return err 136 | } 137 | if err := os.MkdirAll(filepath.Join(wd, "src"), fi.Mode()); err != nil { 138 | return err 139 | } 140 | 141 | if w, err = getCurrentWorkspace(); err != nil { 142 | return err 143 | } 144 | 145 | if len(args) == 0 { 146 | args = []string{getFlag, "vendor"} 147 | } 148 | 149 | gopathsPath := filepath.Join(wd, ConfigDirName, "gopaths") 150 | // if there is no gopaths yet, stick '.' in there. 151 | if _, err := os.Stat(gopathsPath); err != nil { 152 | args = append([]string{"."}, args...) 153 | } 154 | 155 | var fout *os.File 156 | if fout, err = os.Create(gopathsPath); err != nil { 157 | return err 158 | } 159 | defer fout.Close() 160 | 161 | checkGopath := func(gopath string) { 162 | if filepath.IsAbs(gopath) { 163 | fmt.Fprintf(os.Stderr, "%q is not a relative path\n", gopath) 164 | } 165 | } 166 | 167 | goGetDir := "" 168 | 169 | var gopathArgs []string 170 | for i := 0; i < len(args); i++ { 171 | if args[i] == getFlag { 172 | if i+1 >= len(args) { 173 | usage() 174 | } 175 | goGetDir = args[i+1] 176 | checkGopath(goGetDir) 177 | fmt.Fprintln(fout, goGetDir) 178 | i++ 179 | continue 180 | } 181 | 182 | if strings.HasPrefix(args[i], getFlag+"=") { 183 | goGetDir = args[i][len(getFlag+"="):] 184 | 185 | checkGopath(goGetDir) 186 | fmt.Fprintln(fout, goGetDir) 187 | continue 188 | } 189 | 190 | checkGopath(args[i]) 191 | gopathArgs = append(gopathArgs, args[i]) 192 | } 193 | 194 | alreadyListed := map[string]bool{ 195 | goGetDir: true, 196 | } 197 | 198 | for _, gopath := range w.Gopaths { 199 | if _, ok := alreadyListed[gopath]; ok { 200 | continue 201 | } 202 | alreadyListed[gopath] = true 203 | fmt.Fprintln(fout, gopath) 204 | } 205 | for _, gopath := range gopathArgs { 206 | if _, ok := alreadyListed[gopath]; ok { 207 | continue 208 | } 209 | alreadyListed[gopath] = true 210 | fmt.Fprintln(fout, gopath) 211 | } 212 | 213 | return nil 214 | } 215 | -------------------------------------------------------------------------------- /pins.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2015 Google Inc. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "bytes" 18 | "fmt" 19 | "go/build" 20 | "os" 21 | "os/exec" 22 | "path/filepath" 23 | "runtime" 24 | "strings" 25 | 26 | "github.com/skelterjohn/vfu/vend" 27 | ) 28 | 29 | func (w *workspace) getOutsidePackages(targets []string) map[string]string { 30 | os.Setenv("GOPATH", w.Gopath(true)) 31 | 32 | for _, gopath := range w.Gopaths { 33 | target := "./" + gopath + "/src/..." // filepath.Join() doesn't like a leading dot. 34 | targets = append(targets, target) 35 | } 36 | 37 | goListTestArgs := []string{"list", "-e", "-f", "{{range .TestImports}}{{.}}\n{{end}}"} 38 | goListTestArgs = append(goListTestArgs, targets...) 39 | // fmt.Printf("%q\n", goListTestArgs) 40 | var testBuf bytes.Buffer 41 | cmd := exec.Command("go", goListTestArgs...) 42 | cmd.Dir = w.Root 43 | cmd.Stdout = &testBuf 44 | orExit(cmd.Run()) 45 | for _, pkg := range strings.Split(testBuf.String(), "\n") { 46 | targets = append(targets, pkg) 47 | } 48 | 49 | goListArgs := []string{"list", "-e", "-f", "{{.ImportPath}}\n{{range .Deps}}{{.}}\n{{end}}"} 50 | goListArgs = append(goListArgs, targets...) 51 | // fmt.Printf("%q\n", goListArgs) 52 | var buf bytes.Buffer 53 | cmd = exec.Command("go", goListArgs...) 54 | cmd.Dir = w.Root 55 | cmd.Stdout = &buf 56 | orExit(cmd.Run()) 57 | 58 | goroot := runtime.GOROOT() 59 | build.Default.GOPATH = w.Gopath(true) 60 | 61 | pkgs := map[string]string{} 62 | for _, pkg := range strings.Split(buf.String(), "\n") { 63 | if pkg == "" { 64 | continue 65 | } 66 | p, err := build.Import(pkg, w.Root, build.FindOnly) 67 | if err != nil { 68 | continue 69 | } 70 | if x, err := filepath.Rel(goroot, p.Dir); err == nil && !strings.HasPrefix(x, "..") { 71 | continue 72 | } 73 | pkgs[pkg] = p.Dir 74 | } 75 | 76 | for pkg, dir := range pkgs { 77 | if !filepath.IsAbs(dir) { 78 | continue 79 | } 80 | if x, err := filepath.Rel(w.Root, dir); err == nil && !strings.HasPrefix(x, "..") { 81 | continue 82 | } 83 | pkgs[pkg] = dir 84 | } 85 | 86 | return pkgs 87 | } 88 | 89 | func save(w *workspace, args []string) { 90 | 91 | var targets []string 92 | godeps := false 93 | for _, t := range args { 94 | if t == "--godeps" { 95 | godeps = true 96 | } else { 97 | targets = append(targets, t) 98 | } 99 | } 100 | 101 | pkgs := w.getOutsidePackages(targets) 102 | 103 | addonMapping := map[string]string{} 104 | for pkg, dir := range pkgs { 105 | destination := filepath.Join(w.vendorRootSrc(), pkg) 106 | // if it's already in here, vendor will pick it up 107 | if !filepath.IsAbs(dir) { 108 | continue 109 | } 110 | if x, err := filepath.Rel(w.Root, dir); err == nil && !strings.HasPrefix(x, "..") { 111 | continue 112 | } 113 | addonMapping[destination] = dir 114 | } 115 | 116 | var addons []string 117 | for destination, dir := range addonMapping { 118 | addons = append(addons, destination+"="+dir) 119 | } 120 | 121 | var rgits, rhgs []string 122 | if godeps { 123 | for _, dd := range w.importGodeps() { 124 | rarg := dd.root + "=" + dd.repo + "@" + dd.rev 125 | switch dd.kind { 126 | case "git": 127 | rgits = append(rgits, rarg) 128 | case "hg": 129 | rhgs = append(rhgs, rarg) 130 | default: 131 | fmt.Fprintf(os.Stderr, "unsupported VCS %q\n", dd.kind) 132 | } 133 | } 134 | } 135 | 136 | ignoreDirs := []string{".git", ".hg", ".gocfg"} 137 | for _, gopath := range w.Gopaths { 138 | ignoreDirs = append(ignoreDirs, 139 | filepath.Join(gopath, "pkg"), 140 | filepath.Join(gopath, "bin")) 141 | } 142 | ignored := map[string]bool{} 143 | for _, dir := range ignoreDirs { 144 | ignored[dir] = true 145 | } 146 | 147 | cfgPath := filepath.Join(w.Root, ConfigDirName, "vendor.json") 148 | 149 | vend.Save(w.Root, cfgPath, addons, rgits, rhgs, ignored, true) 150 | } 151 | 152 | func vendor(w *workspace, targets []string) { 153 | pkgs := w.getOutsidePackages(targets) 154 | 155 | firstGopath := "." 156 | if len(w.Gopaths) != 0 { 157 | firstGopath = w.Gopaths[0] 158 | } 159 | 160 | for pkg, dir := range pkgs { 161 | destination := filepath.Join(firstGopath, "src", pkg) 162 | // if it's already in here, vendor will pick it up 163 | if !filepath.IsAbs(dir) { 164 | continue 165 | } 166 | if x, err := filepath.Rel(w.Root, dir); err == nil && !strings.HasPrefix(x, "..") { 167 | continue 168 | } 169 | if _, err := os.Stat(destination); err == nil { 170 | continue 171 | } 172 | fmt.Println(pkg) 173 | copyDir(dir, destination) 174 | } 175 | } 176 | 177 | func restore(w *workspace) { 178 | cfgPath := filepath.Join(w.Root, ConfigDirName, "vendor.json") 179 | 180 | vend.Restore(w.Root, cfgPath) 181 | } 182 | -------------------------------------------------------------------------------- /purge.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 Google Inc. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "fmt" 18 | "go/build" 19 | "os" 20 | "path/filepath" 21 | "sort" 22 | "strings" 23 | ) 24 | 25 | // Purge directories in the indicated gopaths if they to not contain source 26 | // referenced from a non-indicated gopath. 27 | func purge(w *workspace, args []string) { 28 | confirmed := false 29 | var gopaths []string 30 | for _, a := range args { 31 | if a == "--confirm" { 32 | confirmed = true 33 | continue 34 | } 35 | gopaths = append(gopaths, a) 36 | } 37 | bctx := build.Default 38 | bctx.GOPATH = w.Gopath(false) 39 | 40 | if len(gopaths) == 0 { 41 | gopaths = w.Gopaths[:1] // By default, the first one is vendor/. 42 | } 43 | if len(gopaths) == 0 { 44 | fmt.Fprintf(os.Stderr, "must purge at least one GOPATH\n") 45 | os.Exit(1) 46 | } 47 | wgps := map[string]bool{} 48 | for _, wpg := range w.Gopaths { 49 | wgps[wpg] = true 50 | } 51 | pgs := map[string]bool{} 52 | for _, pg := range gopaths { 53 | pgs[pg] = true 54 | if !wgps[pg] { 55 | fmt.Fprintf(os.Stderr, "unknown GOPATH %q", pg) 56 | os.Exit(1) 57 | } 58 | } 59 | if len(gopaths) == len(w.Gopaths) { 60 | fmt.Fprintf(os.Stderr, "cannot purge all GOPATHs; try 'rm -r' instead\n") 61 | os.Exit(1) 62 | } 63 | 64 | // Collect a set of safe directories that will not get purged. 65 | safeDirs := []string{} 66 | // Keep them in a map too, to protect against loops. 67 | safeDirsAll := map[string]bool{} 68 | // Start by adding all directories in the non-purged gopaths. 69 | for _, wpg := range w.Gopaths { 70 | if pgs[wpg] { 71 | // skip the purged ones 72 | continue 73 | } 74 | // Only deal with abs paths from here on out, to make checking easier. 75 | if !filepath.IsAbs(wpg) { 76 | wpg = filepath.Join(w.Root, wpg) 77 | } 78 | filepath.Walk(filepath.Join(wpg, "src"), func(path string, info os.FileInfo, err error) error { 79 | if info.IsDir() { 80 | safeDirs = append(safeDirs, path) 81 | safeDirsAll[path] = true 82 | } 83 | return nil 84 | }) 85 | } 86 | 87 | // Go through each safe dir and add its subsafedirs to the end of the list. 88 | for i := 0; i < len(safeDirs); i++ { 89 | deps, err := getDepDirs(bctx, safeDirs[i]) 90 | if err != nil { 91 | fmt.Fprintf(os.Stderr, "problem inspecting %s: %v\n", safeDirs[i], err) 92 | os.Exit(1) 93 | } 94 | for _, d := range deps { 95 | if safeDirsAll[d] { 96 | // cut off cycles 97 | continue 98 | } 99 | safeDirs = append(safeDirs, d) 100 | safeDirsAll[d] = true 101 | } 102 | } 103 | 104 | // Expand the list of safe dirs to be all parents of safe dirs, to make checking easier later. 105 | for dir := range safeDirsAll { 106 | for _, parent := range getAllParents(dir) { 107 | safeDirsAll[parent] = true 108 | } 109 | } 110 | 111 | // Armed with a list of safe dirs, go through gopaths and purge those that aren't safe. 112 | dirsToPurge := map[string]bool{} 113 | for _, pg := range gopaths { 114 | if !filepath.IsAbs(pg) { 115 | pg = filepath.Join(w.Root, pg) 116 | } 117 | filepath.Walk(filepath.Join(pg, "src"), func(path string, info os.FileInfo, err error) error { 118 | if !info.IsDir() { 119 | return nil 120 | } 121 | // If this directory is safe, or is the parent of somethinge safe, we keep it. 122 | // We stored all the parents of the safe directories so we only need to do a single check here. 123 | if safeDirsAll[path] { 124 | return nil 125 | } 126 | // Not safe, will be purged. 127 | dirsToPurge[path] = true 128 | return nil 129 | }) 130 | } 131 | 132 | for d := range dirsToPurge { 133 | // If we're already removing a parent, forget about this directory. 134 | pds := getAllParents(d) 135 | for _, pd := range pds { 136 | if dirsToPurge[pd] { 137 | dirsToPurge[d] = false 138 | } else { 139 | //fmt.Println("no parent", pd, d) 140 | } 141 | } 142 | } 143 | 144 | sortedPurge := []string{} 145 | for d, rm := range dirsToPurge { 146 | if rm { 147 | rd, err := filepath.Rel(w.Root, d) 148 | if err != nil { 149 | fmt.Fprintf(os.Stderr, "problem with relative path for %q: %v\n", d, err) 150 | os.Exit(1) 151 | } 152 | if strings.HasPrefix(rd, "..") { 153 | fmt.Fprintf(os.Stderr, "skipping path outside of workspace %q", d) 154 | continue 155 | } 156 | sortedPurge = append(sortedPurge, rd) 157 | } 158 | } 159 | sort.Strings(sortedPurge) 160 | 161 | if !confirmed { 162 | fmt.Fprintln(os.Stderr, "Directories containing no imported source:") 163 | for _, d := range sortedPurge { 164 | fmt.Println(d) 165 | } 166 | fmt.Fprintln(os.Stderr, "To delete the listed directories, run this command again with '--confirm'.") 167 | os.Exit(0) 168 | } 169 | 170 | for _, d := range sortedPurge { 171 | if err := os.RemoveAll(filepath.Join(w.Root, d)); err != nil { 172 | fmt.Println("Error removing %q: %v\n", d, err) 173 | } 174 | } 175 | 176 | } 177 | 178 | func getDepDirs(bctx build.Context, dir string) ([]string, error) { 179 | pkg, err := bctx.ImportDir(dir, 0) 180 | if err != nil { 181 | if _, ok := err.(*build.NoGoError); !ok { 182 | return nil, err 183 | } 184 | } 185 | depDirs := []string{} 186 | for _, imp := range pkg.Imports { 187 | depPkg, err := bctx.Import(imp, dir, 0) 188 | if err == nil { 189 | depDirs = append(depDirs, depPkg.Dir) 190 | } 191 | } 192 | return depDirs, nil 193 | } 194 | 195 | func getAllParents(dir string) []string { 196 | var parents []string 197 | for { 198 | parent, _ := filepath.Split(dir) 199 | parent = filepath.Clean(parent) 200 | if parent == dir { 201 | return parents 202 | } 203 | parents = append(parents, parent) 204 | dir = parent 205 | } 206 | } 207 | -------------------------------------------------------------------------------- /wgo-exec/README.md: -------------------------------------------------------------------------------- 1 | The wgo-exec tool executes arbitrary commands, with GOPATH set as appropriate for the current wgo workspace, including those that were build from the current wgo workspace. 2 | 3 | In a bash shell, `wgo-exec foo bar` is equivalent to running `GOPATH=$(wgo env GOPATH) foo bar`, with the PATH modified to include the various workspace bin directories. However, sometimes it's easier to change a command than to directly change the environment for a command. 4 | -------------------------------------------------------------------------------- /wgo-exec/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2015 Google Inc. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | /* 15 | The wgo tool is a small wrapper around the go tool. It adds the concept 16 | of a workspace, in addition to that of GOPATH, and several new commands 17 | to manage that workspace. 18 | */ 19 | package main 20 | 21 | import ( 22 | "fmt" 23 | "os" 24 | "os/exec" 25 | "path/filepath" 26 | "strings" 27 | 28 | "github.com/skelterjohn/wgo/workspaces" 29 | ) 30 | 31 | func main() { 32 | w, err := workspaces.GetCurrentWorkspace() 33 | if err != nil { 34 | fmt.Fprintln(os.Stderr, err) 35 | os.Exit(1) 36 | } 37 | 38 | if len(os.Args) < 2 { 39 | fmt.Fprintln(os.Stderr, "Usage: wgo-exec COMMAND [ARG+]") 40 | os.Exit(1) 41 | } 42 | 43 | path := os.Getenv("PATH") 44 | gopath := w.Gopath(true) 45 | sep := string(os.PathListSeparator) 46 | for _, p := range strings.Split(gopath, sep) { 47 | path = filepath.Join(p, "bin") + sep + path 48 | } 49 | 50 | os.Setenv("GOPATH", gopath) 51 | os.Setenv("PATH", path) 52 | cmd := exec.Command(os.Args[1], os.Args[2:]...) 53 | cmd.Stdout = os.Stdout 54 | cmd.Stderr = os.Stderr 55 | if err := cmd.Run(); err != nil { 56 | fmt.Fprintln(os.Stderr, err) 57 | os.Exit(1) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /workspaces.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2015 Google Inc. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package main 15 | 16 | import ( 17 | "log" 18 | "os" 19 | "os/exec" 20 | "path/filepath" 21 | 22 | "github.com/skelterjohn/wgo/workspaces" 23 | ) 24 | 25 | type workspace struct { 26 | workspaces.Workspace 27 | } 28 | 29 | func getCurrentWorkspace() (*workspace, error) { 30 | if w, err := workspaces.GetCurrentWorkspace(); err != nil { 31 | return nil, err 32 | } else { 33 | return &workspace{*w}, nil 34 | } 35 | } 36 | 37 | func getWorkspace(start string) (*workspace, error) { 38 | if w, err := workspaces.GetWorkspace(start); err != nil { 39 | return nil, err 40 | } else { 41 | return &workspace{*w}, nil 42 | } 43 | } 44 | 45 | func guessGoCommand(args []string) string { 46 | if len(args) < 1 { 47 | return "" 48 | } 49 | return args[1] 50 | } 51 | 52 | func (w *workspace) shellOutToGo(args []string) { 53 | // we want to fetch new code directly into the workspace, for convenience 54 | gopath := w.Gopath(guessGoCommand(args) != "get") 55 | os.Setenv("GOPATH", gopath) 56 | log.Printf("using GOPATH=%s", gopath) 57 | shellOutToGo(args) 58 | } 59 | 60 | func (w *workspace) vendorRootSrc() string { 61 | firstGopath := "." 62 | if len(w.Gopaths) != 0 { 63 | firstGopath = w.Gopaths[0] 64 | } 65 | return filepath.Join(firstGopath, "src") 66 | } 67 | 68 | func shellOutToGo(args []string) { 69 | log.Printf("forking to go: %q", args[1:]) 70 | cmd := exec.Command("go", args[1:]...) 71 | cmd.Stdin = os.Stdin 72 | cmd.Stdout = os.Stdout 73 | cmd.Stderr = os.Stderr 74 | err := cmd.Run() 75 | if _, ok := err.(*exec.ExitError); ok { 76 | os.Exit(1) 77 | } 78 | os.Exit(0) 79 | } 80 | -------------------------------------------------------------------------------- /workspaces/workspaces.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2015 Google Inc. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | Unless required by applicable law or agreed to in writing, software 8 | distributed under the License is distributed on an "AS IS" BASIS, 9 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | See the License for the specific language governing permissions and 11 | limitations under the License. 12 | */ 13 | 14 | package workspaces 15 | 16 | import ( 17 | "bufio" 18 | "errors" 19 | "log" 20 | "os" 21 | "os/exec" 22 | "path/filepath" 23 | "strings" 24 | ) 25 | 26 | const ( 27 | ConfigDirName = ".gocfg" 28 | ) 29 | 30 | type Workspace struct { 31 | Root string 32 | Gopaths []string 33 | } 34 | 35 | func GetCurrentWorkspace() (*Workspace, error) { 36 | wd, err := os.Getwd() 37 | if err != nil { 38 | return nil, err 39 | } 40 | return GetWorkspace(wd) 41 | } 42 | 43 | func GetWorkspace(start string) (*Workspace, error) { 44 | goCfgPath := filepath.Join(start, ConfigDirName) 45 | 46 | if fi, err := os.Stat(goCfgPath); err == nil && fi.IsDir() { 47 | w := &Workspace{ 48 | Root: start, 49 | } 50 | if cfgFile, err := os.Open(filepath.Join(goCfgPath, "gopaths")); err == nil { 51 | sc := bufio.NewScanner(cfgFile) 52 | for sc.Scan() { 53 | gopath := sc.Text() 54 | w.Gopaths = append(w.Gopaths, strings.TrimSpace(gopath)) 55 | } 56 | } 57 | return w, nil 58 | } 59 | 60 | if rune(start[len(start)-1]) == filepath.Separator { 61 | start = start[:len(start)-1] 62 | } 63 | dir, _ := filepath.Split(start) 64 | if dir == start { 65 | return nil, errors.New("no workspace") 66 | } 67 | 68 | return GetWorkspace(dir) 69 | } 70 | 71 | func (w *Workspace) Gopath(external bool) string { 72 | var oldgopath string 73 | if external { 74 | oldgopath = os.Getenv("GOPATH") 75 | } 76 | var absGoPaths []string 77 | for _, gopath := range w.Gopaths { 78 | absGoPaths = append(absGoPaths, filepath.Join(w.Root, gopath)) 79 | } 80 | newgopath := strings.Join(absGoPaths, string(filepath.ListSeparator)) 81 | if oldgopath != "" { 82 | newgopath = strings.Join([]string{newgopath, oldgopath}, string(filepath.ListSeparator)) 83 | } 84 | return newgopath 85 | } 86 | 87 | func guessGoCommand(args []string) string { 88 | if len(args) < 1 { 89 | return "" 90 | } 91 | return args[1] 92 | } 93 | 94 | func (w *Workspace) ShellOutToGo(args []string) { 95 | // we want to fetch new code directly into the workspace, for convenience 96 | gopath := w.Gopath(guessGoCommand(args) != "get") 97 | os.Setenv("GOPATH", gopath) 98 | log.Printf("using GOPATH=%s", gopath) 99 | shellOutToGo(args) 100 | } 101 | 102 | func shellOutToGo(args []string) { 103 | log.Printf("forking to go: %q", args[1:]) 104 | cmd := exec.Command("go", args[1:]...) 105 | cmd.Stdin = os.Stdin 106 | cmd.Stdout = os.Stdout 107 | cmd.Stderr = os.Stderr 108 | err := cmd.Run() 109 | if _, ok := err.(*exec.ExitError); ok { 110 | os.Exit(1) 111 | } 112 | os.Exit(0) 113 | } 114 | --------------------------------------------------------------------------------