├── .gitignore ├── CONTRIBUTING.md ├── LICENSE.md ├── Makefile ├── README.md ├── go-shlex ├── COPYING ├── README.md ├── shlex.go └── shlex_test.go ├── main.go └── scantestgen └── main.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | In general, the code posted to the [SmartyStreets github organization](https://github.com/smartystreets) is created to solve specific problems at SmartyStreets that are ancillary to our core products in the address verification industry and may or may not be useful to other organizations or developers. Our reason for posting said code isn't necessarily to solicit feedback or contributions from the community but more as a showcase of some of the approaches to solving problems we have adopted. 4 | 5 | Having stated that, we do consider issues raised by other githubbers as well as contributions submitted via pull requests. When submitting such a pull request, please follow these guidelines: 6 | 7 | - _Look before you leap:_ If the changes you plan to make are significant, it's in everyone's best interest for you to discuss them with a SmartyStreets team member prior to opening a pull request. 8 | - _License and ownership:_ If modifying the `LICENSE.md` file, limit your changes to fixing typographical mistakes. Do NOT modify the actual terms in the license or the copyright by **SmartyStreets, LLC**. Code submitted to SmartyStreets projects becomes property of SmartyStreets and must be compatible with the associated license. 9 | - _Testing:_ If the code you are submitting resides in packages/modules covered by automated tests, be sure to add passing tests that cover your changes and assert expected behavior and state. Submit the additional test cases as part of your change set. 10 | - _Style:_ Match your approach to **naming** and **formatting** with the surrounding code. Basically, the code you submit shouldn't stand out. 11 | - "Naming" refers to such constructs as variables, methods, functions, classes, structs, interfaces, packages, modules, directories, files, etc... 12 | - "Formatting" refers to such constructs as whitespace, horizontal line length, vertical function length, vertical file length, indentation, curly braces, etc... 13 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 SmartyStreets, LLC 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | 21 | NOTE: Various optional and subordinate components carry their own licensing 22 | requirements and restrictions. Use of those components is subject to the terms 23 | and conditions outlined the respective license of each component. 24 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | 3 | # This Makefile is an example of what you could feed to scantest's -command flag. 4 | 5 | test: 6 | go build ./... 7 | go test -short ./... 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # scantest 2 | 3 | A simple, responsive (a word which here means 'snappy') test runner. Like GoConvey, but smarter about what package to run, and with a much simpler interface, and at a fraction of the LOC. 4 | 5 | ## Features 6 | 7 | - Runs `make` or `go test` or any command you supply whenever a .go file in any package under the current directory changes. 8 | - Provides colorful output according to exit status of tests (green=passed, red=failed). 9 | 10 | ### Installation 11 | 12 | ``` 13 | go get github.com/smartystreets/scantest 14 | ``` 15 | 16 | ### Console Runner Execution 17 | 18 | ``` 19 | cd my-project 20 | scantest 21 | ``` 22 | 23 | Results of your tests will display in the terminal until you enter `+c`. 24 | 25 | ## Can I run it in the browser? 26 | 27 | Yes, with [gotty](https://github.com/yudai/gotty): 28 | 29 | ``` 30 | $ gotty scantest 31 | ``` 32 | 33 | Open a web browser to http://localhost:8080 to see the auto-updating results. 34 | 35 | 36 | ## Custom Go Test Arguments 37 | 38 | Simple supply a Makefile in the current directory and specify what command and arguments to run. Then just run scantest (it will find your makefile and run the default action, which you can change whenever necessary). 39 | 40 | Example: 41 | 42 | ``` 43 | #!/usr/bin/make -f 44 | 45 | test: 46 | go test -v -short -run=TestSomething -race 47 | ``` 48 | -------------------------------------------------------------------------------- /go-shlex/COPYING: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /go-shlex/README.md: -------------------------------------------------------------------------------- 1 | go-shlex is a simple lexer for go that supports shell-style quoting, 2 | commenting, and escaping. 3 | -------------------------------------------------------------------------------- /go-shlex/shlex.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2012 Google Inc. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package shlex 18 | 19 | /* 20 | Package shlex implements a simple lexer which splits input in to tokens using 21 | shell-style rules for quoting and commenting. 22 | */ 23 | import ( 24 | "bufio" 25 | "errors" 26 | "fmt" 27 | "io" 28 | "strings" 29 | ) 30 | 31 | /* 32 | A TokenType is a top-level token; a word, space, comment, unknown. 33 | */ 34 | type TokenType int 35 | 36 | /* 37 | A RuneTokenType is the type of a UTF-8 character; a character, quote, space, escape. 38 | */ 39 | type RuneTokenType int 40 | 41 | type lexerState int 42 | 43 | type Token struct { 44 | tokenType TokenType 45 | value string 46 | } 47 | 48 | /* 49 | Two tokens are equal if both their types and values are equal. A nil token can 50 | never equal another token. 51 | */ 52 | func (a *Token) Equal(b *Token) bool { 53 | if a == nil || b == nil { 54 | return false 55 | } 56 | if a.tokenType != b.tokenType { 57 | return false 58 | } 59 | return a.value == b.value 60 | } 61 | 62 | const ( 63 | RUNE_CHAR string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-,/@$*()+=><:;&^%~|!?[]{}" 64 | RUNE_SPACE string = " \t\r\n" 65 | RUNE_ESCAPING_QUOTE string = "\"" 66 | RUNE_NONESCAPING_QUOTE string = "'" 67 | RUNE_ESCAPE = "\\" 68 | RUNE_COMMENT = "#" 69 | 70 | RUNETOKEN_UNKNOWN RuneTokenType = 0 71 | RUNETOKEN_CHAR RuneTokenType = 1 72 | RUNETOKEN_SPACE RuneTokenType = 2 73 | RUNETOKEN_ESCAPING_QUOTE RuneTokenType = 3 74 | RUNETOKEN_NONESCAPING_QUOTE RuneTokenType = 4 75 | RUNETOKEN_ESCAPE RuneTokenType = 5 76 | RUNETOKEN_COMMENT RuneTokenType = 6 77 | RUNETOKEN_EOF RuneTokenType = 7 78 | 79 | TOKEN_UNKNOWN TokenType = 0 80 | TOKEN_WORD TokenType = 1 81 | TOKEN_SPACE TokenType = 2 82 | TOKEN_COMMENT TokenType = 3 83 | 84 | STATE_START lexerState = 0 85 | STATE_INWORD lexerState = 1 86 | STATE_ESCAPING lexerState = 2 87 | STATE_ESCAPING_QUOTED lexerState = 3 88 | STATE_QUOTED_ESCAPING lexerState = 4 89 | STATE_QUOTED lexerState = 5 90 | STATE_COMMENT lexerState = 6 91 | 92 | INITIAL_TOKEN_CAPACITY int = 100 93 | ) 94 | 95 | /* 96 | A type for classifying characters. This allows for different sorts of 97 | classifiers - those accepting extended non-ascii chars, or strict posix 98 | compatibility, for example. 99 | */ 100 | type TokenClassifier struct { 101 | typeMap map[int32]RuneTokenType 102 | } 103 | 104 | func addRuneClass(typeMap *map[int32]RuneTokenType, runes string, tokenType RuneTokenType) { 105 | for _, rune := range runes { 106 | (*typeMap)[int32(rune)] = tokenType 107 | } 108 | } 109 | 110 | /* 111 | Create a new classifier for basic ASCII characters. 112 | */ 113 | func NewDefaultClassifier() *TokenClassifier { 114 | typeMap := map[int32]RuneTokenType{} 115 | addRuneClass(&typeMap, RUNE_CHAR, RUNETOKEN_CHAR) 116 | addRuneClass(&typeMap, RUNE_SPACE, RUNETOKEN_SPACE) 117 | addRuneClass(&typeMap, RUNE_ESCAPING_QUOTE, RUNETOKEN_ESCAPING_QUOTE) 118 | addRuneClass(&typeMap, RUNE_NONESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE) 119 | addRuneClass(&typeMap, RUNE_ESCAPE, RUNETOKEN_ESCAPE) 120 | addRuneClass(&typeMap, RUNE_COMMENT, RUNETOKEN_COMMENT) 121 | return &TokenClassifier{ 122 | typeMap: typeMap} 123 | } 124 | 125 | func (classifier *TokenClassifier) ClassifyRune(rune int32) RuneTokenType { 126 | return classifier.typeMap[rune] 127 | } 128 | 129 | /* 130 | A type for turning an input stream in to a sequence of strings. Whitespace and 131 | comments are skipped. 132 | */ 133 | type Lexer struct { 134 | tokenizer *Tokenizer 135 | } 136 | 137 | /* 138 | Create a new lexer. 139 | */ 140 | func NewLexer(r io.Reader) (*Lexer, error) { 141 | 142 | tokenizer, err := NewTokenizer(r) 143 | if err != nil { 144 | return nil, err 145 | } 146 | lexer := &Lexer{tokenizer: tokenizer} 147 | return lexer, nil 148 | } 149 | 150 | /* 151 | Return the next word, and an error value. If there are no more words, the error 152 | will be io.EOF. 153 | */ 154 | func (l *Lexer) NextWord() (string, error) { 155 | var token *Token 156 | var err error 157 | for { 158 | token, err = l.tokenizer.NextToken() 159 | if err != nil { 160 | return "", err 161 | } 162 | switch token.tokenType { 163 | case TOKEN_WORD: 164 | { 165 | return token.value, nil 166 | } 167 | case TOKEN_COMMENT: 168 | { 169 | // skip comments 170 | } 171 | default: 172 | { 173 | panic(fmt.Sprintf("Unknown token type: %v", token.tokenType)) 174 | } 175 | } 176 | } 177 | return "", io.EOF 178 | } 179 | 180 | /* 181 | A type for turning an input stream in to a sequence of typed tokens. 182 | */ 183 | type Tokenizer struct { 184 | input *bufio.Reader 185 | classifier *TokenClassifier 186 | } 187 | 188 | /* 189 | Create a new tokenizer. 190 | */ 191 | func NewTokenizer(r io.Reader) (*Tokenizer, error) { 192 | input := bufio.NewReader(r) 193 | classifier := NewDefaultClassifier() 194 | tokenizer := &Tokenizer{ 195 | input: input, 196 | classifier: classifier} 197 | return tokenizer, nil 198 | } 199 | 200 | /* 201 | Scan the stream for the next token. 202 | 203 | This uses an internal state machine. It will panic if it encounters a character 204 | which it does not know how to handle. 205 | */ 206 | func (t *Tokenizer) scanStream() (*Token, error) { 207 | state := STATE_START 208 | var tokenType TokenType 209 | value := make([]int32, 0, INITIAL_TOKEN_CAPACITY) 210 | var ( 211 | nextRune int32 212 | nextRuneType RuneTokenType 213 | err error 214 | ) 215 | SCAN: 216 | for { 217 | nextRune, _, err = t.input.ReadRune() 218 | nextRuneType = t.classifier.ClassifyRune(nextRune) 219 | if err != nil { 220 | if err == io.EOF { 221 | nextRuneType = RUNETOKEN_EOF 222 | err = nil 223 | } else { 224 | return nil, err 225 | } 226 | } 227 | switch state { 228 | case STATE_START: // no runes read yet 229 | { 230 | switch nextRuneType { 231 | case RUNETOKEN_EOF: 232 | { 233 | return nil, io.EOF 234 | } 235 | case RUNETOKEN_CHAR: 236 | { 237 | tokenType = TOKEN_WORD 238 | value = append(value, nextRune) 239 | state = STATE_INWORD 240 | } 241 | case RUNETOKEN_SPACE: 242 | { 243 | } 244 | case RUNETOKEN_ESCAPING_QUOTE: 245 | { 246 | tokenType = TOKEN_WORD 247 | state = STATE_QUOTED_ESCAPING 248 | } 249 | case RUNETOKEN_NONESCAPING_QUOTE: 250 | { 251 | tokenType = TOKEN_WORD 252 | state = STATE_QUOTED 253 | } 254 | case RUNETOKEN_ESCAPE: 255 | { 256 | tokenType = TOKEN_WORD 257 | state = STATE_ESCAPING 258 | } 259 | case RUNETOKEN_COMMENT: 260 | { 261 | tokenType = TOKEN_COMMENT 262 | state = STATE_COMMENT 263 | } 264 | default: 265 | { 266 | return nil, errors.New(fmt.Sprintf("Unknown rune: %v", nextRune)) 267 | } 268 | } 269 | } 270 | case STATE_INWORD: // in a regular word 271 | { 272 | switch nextRuneType { 273 | case RUNETOKEN_EOF: 274 | { 275 | break SCAN 276 | } 277 | case RUNETOKEN_CHAR, RUNETOKEN_COMMENT: 278 | { 279 | value = append(value, nextRune) 280 | } 281 | case RUNETOKEN_SPACE: 282 | { 283 | t.input.UnreadRune() 284 | break SCAN 285 | } 286 | case RUNETOKEN_ESCAPING_QUOTE: 287 | { 288 | state = STATE_QUOTED_ESCAPING 289 | } 290 | case RUNETOKEN_NONESCAPING_QUOTE: 291 | { 292 | state = STATE_QUOTED 293 | } 294 | case RUNETOKEN_ESCAPE: 295 | { 296 | state = STATE_ESCAPING 297 | } 298 | default: 299 | { 300 | return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) 301 | } 302 | } 303 | } 304 | case STATE_ESCAPING: // the next rune after an escape character 305 | { 306 | switch nextRuneType { 307 | case RUNETOKEN_EOF: 308 | { 309 | err = errors.New("EOF found after escape character") 310 | break SCAN 311 | } 312 | case RUNETOKEN_CHAR, RUNETOKEN_SPACE, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT: 313 | { 314 | state = STATE_INWORD 315 | value = append(value, nextRune) 316 | } 317 | default: 318 | { 319 | return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) 320 | } 321 | } 322 | } 323 | case STATE_ESCAPING_QUOTED: // the next rune after an escape character, in double quotes 324 | { 325 | switch nextRuneType { 326 | case RUNETOKEN_EOF: 327 | { 328 | err = errors.New("EOF found after escape character") 329 | break SCAN 330 | } 331 | case RUNETOKEN_CHAR, RUNETOKEN_SPACE, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT: 332 | { 333 | state = STATE_QUOTED_ESCAPING 334 | value = append(value, nextRune) 335 | } 336 | default: 337 | { 338 | return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) 339 | } 340 | } 341 | } 342 | case STATE_QUOTED_ESCAPING: // in escaping double quotes 343 | { 344 | switch nextRuneType { 345 | case RUNETOKEN_EOF: 346 | { 347 | err = errors.New("EOF found when expecting closing quote.") 348 | break SCAN 349 | } 350 | case RUNETOKEN_CHAR, RUNETOKEN_UNKNOWN, RUNETOKEN_SPACE, RUNETOKEN_NONESCAPING_QUOTE, RUNETOKEN_COMMENT: 351 | { 352 | value = append(value, nextRune) 353 | } 354 | case RUNETOKEN_ESCAPING_QUOTE: 355 | { 356 | state = STATE_INWORD 357 | } 358 | case RUNETOKEN_ESCAPE: 359 | { 360 | state = STATE_ESCAPING_QUOTED 361 | } 362 | default: 363 | { 364 | return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) 365 | } 366 | } 367 | } 368 | case STATE_QUOTED: // in non-escaping single quotes 369 | { 370 | switch nextRuneType { 371 | case RUNETOKEN_EOF: 372 | { 373 | err = errors.New("EOF found when expecting closing quote.") 374 | break SCAN 375 | } 376 | case RUNETOKEN_CHAR, RUNETOKEN_UNKNOWN, RUNETOKEN_SPACE, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT: 377 | { 378 | value = append(value, nextRune) 379 | } 380 | case RUNETOKEN_NONESCAPING_QUOTE: 381 | { 382 | state = STATE_INWORD 383 | } 384 | default: 385 | { 386 | return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) 387 | } 388 | } 389 | } 390 | case STATE_COMMENT: 391 | { 392 | switch nextRuneType { 393 | case RUNETOKEN_EOF: 394 | { 395 | break SCAN 396 | } 397 | case RUNETOKEN_CHAR, RUNETOKEN_UNKNOWN, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT, RUNETOKEN_NONESCAPING_QUOTE: 398 | { 399 | value = append(value, nextRune) 400 | } 401 | case RUNETOKEN_SPACE: 402 | { 403 | if nextRune == '\n' { 404 | state = STATE_START 405 | break SCAN 406 | } else { 407 | value = append(value, nextRune) 408 | } 409 | } 410 | default: 411 | { 412 | return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) 413 | } 414 | } 415 | } 416 | default: 417 | { 418 | panic(fmt.Sprintf("Unexpected state: %v", state)) 419 | } 420 | } 421 | } 422 | token := &Token{ 423 | tokenType: tokenType, 424 | value: string(value)} 425 | return token, err 426 | } 427 | 428 | /* 429 | Return the next token in the stream, and an error value. If there are no more 430 | tokens available, the error value will be io.EOF. 431 | */ 432 | func (t *Tokenizer) NextToken() (*Token, error) { 433 | return t.scanStream() 434 | } 435 | 436 | /* 437 | Split a string in to a slice of strings, based upon shell-style rules for 438 | quoting, escaping, and spaces. 439 | */ 440 | func Split(s string) ([]string, error) { 441 | l, err := NewLexer(strings.NewReader(s)) 442 | if err != nil { 443 | return nil, err 444 | } 445 | subStrings := []string{} 446 | for { 447 | word, err := l.NextWord() 448 | if err != nil { 449 | if err == io.EOF { 450 | return subStrings, nil 451 | } 452 | return subStrings, err 453 | } 454 | subStrings = append(subStrings, word) 455 | } 456 | return subStrings, nil 457 | } 458 | -------------------------------------------------------------------------------- /go-shlex/shlex_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2012 Google Inc. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package shlex 18 | 19 | import ( 20 | "strings" 21 | "testing" 22 | ) 23 | 24 | func checkError(err error, t *testing.T) { 25 | if err != nil { 26 | t.Error(err) 27 | } 28 | } 29 | 30 | func TestClassifier(t *testing.T) { 31 | classifier := NewDefaultClassifier() 32 | runeTests := map[int32]RuneTokenType{ 33 | 'a': RUNETOKEN_CHAR, 34 | ' ': RUNETOKEN_SPACE, 35 | '"': RUNETOKEN_ESCAPING_QUOTE, 36 | '\'': RUNETOKEN_NONESCAPING_QUOTE, 37 | '#': RUNETOKEN_COMMENT} 38 | for rune, expectedType := range runeTests { 39 | foundType := classifier.ClassifyRune(rune) 40 | if foundType != expectedType { 41 | t.Logf("Expected type: %v for rune '%c'(%v). Found type: %v.", expectedType, rune, rune, foundType) 42 | t.Fail() 43 | } 44 | } 45 | } 46 | 47 | func TestTokenizer(t *testing.T) { 48 | testInput := strings.NewReader("one two \"three four\" \"five \\\"six\\\"\" seven#eight # nine # ten\n eleven") 49 | expectedTokens := []*Token{ 50 | &Token{ 51 | tokenType: TOKEN_WORD, 52 | value: "one"}, 53 | &Token{ 54 | tokenType: TOKEN_WORD, 55 | value: "two"}, 56 | &Token{ 57 | tokenType: TOKEN_WORD, 58 | value: "three four"}, 59 | &Token{ 60 | tokenType: TOKEN_WORD, 61 | value: "five \"six\""}, 62 | &Token{ 63 | tokenType: TOKEN_WORD, 64 | value: "seven#eight"}, 65 | &Token{ 66 | tokenType: TOKEN_COMMENT, 67 | value: " nine # ten"}, 68 | &Token{ 69 | tokenType: TOKEN_WORD, 70 | value: "eleven"}} 71 | 72 | tokenizer, err := NewTokenizer(testInput) 73 | checkError(err, t) 74 | for _, expectedToken := range expectedTokens { 75 | foundToken, err := tokenizer.NextToken() 76 | checkError(err, t) 77 | if !foundToken.Equal(expectedToken) { 78 | t.Error("Expected token:", expectedToken, ". Found:", foundToken) 79 | } 80 | } 81 | } 82 | 83 | func TestLexer(t *testing.T) { 84 | testInput := strings.NewReader("one") 85 | expectedWord := "one" 86 | lexer, err := NewLexer(testInput) 87 | checkError(err, t) 88 | foundWord, err := lexer.NextWord() 89 | checkError(err, t) 90 | if expectedWord != foundWord { 91 | t.Error("Expected word:", expectedWord, ". Found:", foundWord) 92 | } 93 | } 94 | 95 | func TestSplitSimple(t *testing.T) { 96 | testInput := "one two three" 97 | expectedOutput := []string{"one", "two", "three"} 98 | foundOutput, err := Split(testInput) 99 | if err != nil { 100 | t.Error("Split returned error:", err) 101 | } 102 | if len(expectedOutput) != len(foundOutput) { 103 | t.Error("Split expected:", len(expectedOutput), "results. Found:", len(foundOutput), "results") 104 | } 105 | for i := range foundOutput { 106 | if foundOutput[i] != expectedOutput[i] { 107 | t.Error("Item:", i, "(", foundOutput[i], ") differs from the expected value:", expectedOutput[i]) 108 | } 109 | } 110 | } 111 | 112 | func TestSplitEscapingQuotes(t *testing.T) { 113 | testInput := "one \"два ${three}\" four" 114 | expectedOutput := []string{"one", "два ${three}", "four"} 115 | foundOutput, err := Split(testInput) 116 | if err != nil { 117 | t.Error("Split returned error:", err) 118 | } 119 | if len(expectedOutput) != len(foundOutput) { 120 | t.Error("Split expected:", len(expectedOutput), "results. Found:", len(foundOutput), "results") 121 | } 122 | for i := range foundOutput { 123 | if foundOutput[i] != expectedOutput[i] { 124 | t.Error("Item:", i, "(", foundOutput[i], ") differs from the expected value:", expectedOutput[i]) 125 | } 126 | } 127 | } 128 | 129 | func TestGlobbingExpressions(t *testing.T) { 130 | testInput := "onefile *file one?ile onefil[de]" 131 | expectedOutput := []string{"onefile", "*file", "one?ile", "onefil[de]"} 132 | foundOutput, err := Split(testInput) 133 | if err != nil { 134 | t.Error("Split returned error", err) 135 | } 136 | if len(expectedOutput) != len(foundOutput) { 137 | t.Error("Split expected:", len(expectedOutput), "results. Found:", len(foundOutput), "results") 138 | } 139 | for i := range foundOutput { 140 | if foundOutput[i] != expectedOutput[i] { 141 | t.Error("Item:", i, "(", foundOutput[i], ") differs from the expected value:", expectedOutput[i]) 142 | } 143 | } 144 | 145 | } 146 | 147 | func TestSplitNonEscapingQuotes(t *testing.T) { 148 | testInput := "one 'два ${three}' four" 149 | expectedOutput := []string{"one", "два ${three}", "four"} 150 | foundOutput, err := Split(testInput) 151 | if err != nil { 152 | t.Error("Split returned error:", err) 153 | } 154 | if len(expectedOutput) != len(foundOutput) { 155 | t.Error("Split expected:", len(expectedOutput), "results. Found:", len(foundOutput), "results") 156 | } 157 | for i := range foundOutput { 158 | if foundOutput[i] != expectedOutput[i] { 159 | t.Error("Item:", i, "(", foundOutput[i], ") differs from the expected value:", expectedOutput[i]) 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "os" 8 | "os/exec" 9 | "path/filepath" 10 | "runtime" 11 | "strings" 12 | "time" 13 | 14 | "github.com/mdwhatcott/spin" 15 | "github.com/smartystreets/scantest/go-shlex" 16 | ) 17 | 18 | func main() { 19 | command := flag.String("command", deriveDefaultCommand(), "The command (with arguments) to run when a .go file is saved.") 20 | flag.Parse() 21 | 22 | working, err := os.Getwd() 23 | if err != nil { 24 | log.Fatal(err) 25 | } 26 | 27 | args, err := shlex.Split(*command) 28 | if err != nil { 29 | log.Fatal(err) 30 | } 31 | if len(args) < 1 { 32 | log.Fatal("Please provide something to run.") 33 | } 34 | 35 | scanner := &Scanner{working: working} 36 | runner := &Runner{working: working, command: args} 37 | for { 38 | if scanner.Scan() { 39 | runner.Run() 40 | } 41 | } 42 | } 43 | 44 | // deriveDefaultCommand determines what to present as the default value of the 45 | // command flag, in case the user does not provide one. It first looks for a 46 | // Makefile in the current directory. If that doesn't exist it looks for the 47 | // Makefile provided by this project, which serves as a working generic example 48 | // that should fit a variety of use cases. If that doesn't exist for whatever 49 | // reason (say, if the scantest binary wasn't built from source on the current 50 | // machine) then it defaults to 'go test'. 51 | func deriveDefaultCommand() string { 52 | var defaultCommand string 53 | 54 | if current, err := os.Getwd(); err == nil { 55 | if _, err := os.Stat(filepath.Join(current, "Makefile")); err == nil { 56 | defaultCommand = "make" 57 | } 58 | } 59 | 60 | if defaultCommand == "" { 61 | if _, file, _, ok := runtime.Caller(0); ok { 62 | backupMakefile := filepath.Join(filepath.Dir(file), "Makefile") 63 | if _, err := os.Stat(backupMakefile); err == nil { 64 | defaultCommand = backupMakefile 65 | } 66 | } 67 | } 68 | 69 | if defaultCommand == "" { 70 | defaultCommand = "go test" 71 | } 72 | 73 | return defaultCommand 74 | } 75 | 76 | //////////////////////////////////////////////////////////////////////////// 77 | 78 | type Scanner struct { 79 | state int64 80 | working string 81 | } 82 | 83 | func (this *Scanner) Scan() bool { 84 | time.Sleep(time.Millisecond * 250) 85 | newState := this.checksum() 86 | defer func() { this.state = newState }() 87 | write(".") 88 | return newState != this.state 89 | } 90 | 91 | func (this *Scanner) checksum() int64 { 92 | var sum int64 = 0 93 | err := filepath.Walk(this.working, func(path string, info os.FileInfo, err error) error { 94 | if info.IsDir() { 95 | sum++ 96 | } else if info.Name() == "generated_by_gunit_test.go" { 97 | return nil 98 | } else if strings.HasSuffix(info.Name(), ".go") || info.Name() == "Makefile" { 99 | sum += info.Size() + info.ModTime().Unix() 100 | } 101 | return nil 102 | }) 103 | if err != nil { 104 | log.Fatal(err) 105 | } 106 | return sum 107 | } 108 | 109 | //////////////////////////////////////////////////////////////////////////// 110 | 111 | type Runner struct { 112 | command []string 113 | working string 114 | } 115 | 116 | func (this *Runner) Run() { 117 | message := fmt.Sprintln(" Executing:", strings.Join(this.command, " ")) 118 | 119 | write(clearScreen) 120 | writeln() 121 | write(strings.Repeat("=", len(message))) 122 | writeln() 123 | write(message) 124 | write(strings.Repeat("=", len(message))) 125 | writeln() 126 | output, success := this.run() 127 | if success { 128 | write(greenColor) 129 | } else { 130 | write(redColor) 131 | } 132 | write(string(output)) 133 | writeln() 134 | write(strings.Repeat("-", len(message))) 135 | writeln() 136 | write(resetColor) 137 | } 138 | 139 | func writeln() { 140 | write("\n") 141 | } 142 | func write(a ...interface{}) { 143 | fmt.Fprint(os.Stdout, a...) 144 | os.Stdout.Sync() 145 | } 146 | 147 | func (this *Runner) run() (output []byte, success bool) { 148 | command := exec.Command(this.command[0]) 149 | if len(this.command) > 1 { 150 | command.Args = append(command.Args, this.command[1:]...) 151 | } 152 | command.Dir = this.working 153 | 154 | now := time.Now() 155 | spinner := spin.New(spin.StyleLine, time.Millisecond*100) 156 | go spinner.Start() 157 | 158 | var err error 159 | output, err = command.CombinedOutput() 160 | spinner.Stop() 161 | fmt.Println(Round(time.Since(now), time.Millisecond)) 162 | if err != nil { 163 | output = append(output, []byte(err.Error())...) 164 | } 165 | return output, command.ProcessState.Success() 166 | } 167 | 168 | // GoLang-Nuts thread: 169 | // https://groups.google.com/d/msg/golang-nuts/OWHmTBu16nA/RQb4TvXUg1EJ 170 | // Wise, a word which here means unhelpful, guidance from Commander Pike: 171 | // https://groups.google.com/d/msg/golang-nuts/OWHmTBu16nA/zoGNwDVKIqAJ 172 | // Answer satisfying the original asker: 173 | // https://groups.google.com/d/msg/golang-nuts/OWHmTBu16nA/wnrz0tNXzngJ 174 | // Answer implementation on the Go Playground: 175 | // http://play.golang.org/p/QHocTHl8iR 176 | func Round(duration, precision time.Duration) time.Duration { 177 | if precision <= 0 { 178 | return duration 179 | } 180 | negative := duration < 0 181 | if negative { 182 | duration = -duration 183 | } 184 | if m := duration % precision; m+m < precision { 185 | duration = duration - m 186 | } else { 187 | duration = duration + precision - m 188 | } 189 | if negative { 190 | return -duration 191 | } 192 | return duration 193 | } 194 | 195 | //////////////////////////////////////////////////////////////////////////// 196 | 197 | var ( 198 | clearScreen = "\033[2J\033[H" // clear the screen and put the cursor at top-left 199 | greenColor = "\033[32m" 200 | redColor = "\033[31m" 201 | resetColor = "\033[0m" 202 | ) 203 | -------------------------------------------------------------------------------- /scantestgen/main.go: -------------------------------------------------------------------------------- 1 | // scantestgen continually scans the current directory for changes to 2 | // _test.go files and runs go generate on the containing package. 3 | // This is useful when working on packages tested using 4 | // github.com/smartystreets/gunit. 5 | package main 6 | 7 | import ( 8 | "log" 9 | "os" 10 | "os/exec" 11 | "path/filepath" 12 | "strings" 13 | "sync" 14 | "time" 15 | ) 16 | 17 | func main() { 18 | for { 19 | scanForChanges(root) 20 | goGenerate() 21 | reset() 22 | } 23 | } 24 | func scanForChanges(root string) { 25 | if err := filepath.Walk(root, scan); err != nil { 26 | log.Fatal(err) 27 | } 28 | 29 | } 30 | 31 | func scan(path string, info os.FileInfo, err error) error { 32 | if isGoTestFile(info) { 33 | fresh[filepath.Dir(path)] += checksum(info) 34 | } 35 | return nil 36 | } 37 | 38 | func isGoTestFile(file os.FileInfo) bool { 39 | return !file.IsDir() && strings.HasSuffix(file.Name(), "_test.go") 40 | } 41 | 42 | func checksum(file os.FileInfo) int64 { 43 | return file.Size() + file.ModTime().Unix() 44 | } 45 | 46 | func goGenerate() { 47 | for directory, state := range fresh { 48 | if stale[directory] != state { 49 | waiter.Add(1) 50 | go generate(directory) 51 | } 52 | } 53 | } 54 | 55 | func generate(path string) { 56 | name := packageName(path) 57 | log.Println("Running go generate for:", name) 58 | output, err := exec.Command("go", "generate", name).CombinedOutput() 59 | if err != nil { 60 | log.Printf("[ERROR] go generate %s:\n%s\n", name, string(output)) 61 | } 62 | waiter.Done() 63 | } 64 | 65 | func packageName(path string) string { 66 | return path[len(goPath)+len("/src/"):] 67 | } 68 | 69 | func reset() { 70 | stale = fresh 71 | fresh = make(map[string]int64) 72 | time.Sleep(interval) 73 | waiter.Wait() 74 | } 75 | 76 | /**************************************************************************/ 77 | 78 | var ( 79 | root = resolveWorkingDirectory() 80 | stale = make(map[string]int64) 81 | fresh = make(map[string]int64) 82 | waiter = new(sync.WaitGroup) 83 | goPath = os.Getenv("GOPATH") 84 | ) 85 | 86 | func resolveWorkingDirectory() string { 87 | root, err := os.Getwd() 88 | if err != nil { 89 | log.Fatal(err) 90 | } 91 | return root 92 | } 93 | 94 | const interval = time.Millisecond * 250 95 | --------------------------------------------------------------------------------