├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── install.sh ├── lib ├── config.go ├── file.go ├── file_test.go ├── fuzzy.go ├── fuzzy_test.go ├── ls.go ├── placeholder.go ├── placeholder_test.go ├── root.go ├── run.go ├── show.go ├── snippet.go ├── snippet_test.go └── utils.go ├── main.go ├── sman.rc └── snippets ├── .gitignore ├── apache.yml ├── apache └── vhost:add ├── aptitude.yml ├── docker.yml ├── elastic.yml ├── github.yml ├── go.yml ├── mysql.yml ├── postgresql.yml ├── puppet.yml ├── shell.yml ├── shell ├── for:file └── sshconfig:add ├── ufw.yml ├── varnish.yml └── vbox.yml /.gitignore: -------------------------------------------------------------------------------- 1 | dots 2 | sman 3 | bin 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.6 5 | - 1.9 6 | 7 | install: 8 | - go get -t ./... 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VERSION := $(shell awk -F= '/version =/ {print $$2}' lib/root.go | tr -d "\" ") 2 | 3 | test: 4 | go test -v ./... 5 | 6 | all: 7 | go build -v 8 | 9 | release: 10 | @$(MAKE) linux_amd64 11 | @$(MAKE) linux_386 12 | @$(MAKE) linux_arm 13 | @$(MAKE) darwin_amd64 14 | 15 | linux_amd64: GOOS=linux 16 | linux_amd64: GOARCH=amd64 17 | linux_amd64: build 18 | 19 | linux_386: GOOS=linux 20 | linux_386: GOARCH=386 21 | linux_386: build 22 | 23 | linux_arm: GOOS=linux 24 | linux_arm: GOARCH=arm 25 | linux_arm: build 26 | 27 | darwin_amd64: GOOS=darwin 28 | darwin_amd64: GOARCH=amd64 29 | darwin_amd64: build 30 | 31 | build: 32 | env GOOS=${GOOS} GOARCH=${GOARCH} go build -o bin/sman-${GOOS}-${GOARCH}-v${VERSION} 33 | cd bin; tar -czf sman-${GOOS}-${GOARCH}-v${VERSION}.tgz sman-${GOOS}-${GOARCH}-v${VERSION} 34 | rm bin/sman-${GOOS}-${GOARCH}-v${VERSION} 35 | 36 | watch: 37 | CompileDaemon -command="go test -v ./..." -color=True --log-prefix=False --exclude-dir=.git 38 | 39 | .PHONY: all release linux_amd64 linux_386 linux_arm \ 40 | darwin_amd64 build test watch 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sman 2 | [![Build Status](https://travis-ci.org/tokozedg/sman.svg?branch=master)](https://travis-ci.org/tokozedg/sman) 3 | 4 | *** 5 | A command-line snippet manager in Go 6 | 7 | [![asciicast](https://asciinema.org/a/2e04fxybyyo5ubjk42mk4yuop.png)](https://asciinema.org/a/2e04fxybyyo5ubjk42mk4yuop) 8 | 9 | ## Install 10 | 11 | ```shell 12 | bash -c "$(curl https://raw.githubusercontent.com/tokozedg/sman/master/install.sh)" 13 | ``` 14 | 15 | ## Building 16 | 17 | * Build with Go 18 | ```bash 19 | go get -v github.com/tokozedg/sman 20 | ``` 21 | 22 | * Add to your rc: 23 | ```bash 24 | [ -f $GOPATH/src/github.com/tokozedg/sman/sman.rc ] && source $GOPATH/src/github.com/tokozedg/sman/sman.rc 25 | ``` 26 | 27 | * Optionally copy demo snippets dir or create yours: 28 | ```bash 29 | cp -r $GOPATH/src/github.com/tokozedg/sman/snippets ~/ 30 | ``` 31 | 32 | ## Snippets Examples 33 | 34 | ```yaml 35 | #~/snippets/shell.yml 36 | 37 | smtp:server: # snippet name 38 | do: exec # copy or exec 39 | desc: smtp server in python. Prints mails to stdout 40 | command: python -m smtpd -n -c DebuggingServer localhost:1025 41 | 42 | ``` 43 | 44 | ```yaml 45 | #~/snippets/shell.yml 46 | # Sman will ask input for placeholder <> 47 | tcpdump:port: 48 | do: copy 49 | desc: listen traffic on port 50 | command: tcpdump -nqt -s 0 -A -i eth0 port <> 51 | ``` 52 | 53 | ```yaml 54 | #~/snippets/shell.yml 55 | # To execute multiline commands, separate lines by semi-colon 56 | curl:upload: 57 | do: exec 58 | command: > 59 | gpg -c <>; 60 | curl --upload-file <>.gpg https://transfer.sh/<>.gpg 61 | ``` 62 | 63 | * You can export command to a separate file located at: `SMAN_SNIPPET_DIR//` 64 | 65 | 66 | 67 | ## Placeholders 68 | 69 | ``` 70 | <> 71 | ``` 72 | * Include placeholder anywhere within snippet command 73 | * Name is the only mandatory field 74 | * You can have multiple placeholders with the same name. After input all of them will be replaced 75 | * Use `\` to escape comma in options 76 | 77 | ## Usage Examples 78 | 79 | ### Run snippet 80 | 81 | ```bash 82 | s run [-f ] [-t ] [placeholder values...] [-cxyp] 83 | ``` 84 | ```bash 85 | ~|⇒ s run -f shell curl:upload test.tar.gz -x 86 | ---- 87 | gpg -c test.tar.gz; curl --upload-file test.tar.gz.gpg https://transfer.sh/test.tar.gz.gpg 88 | ---- 89 | Execute Snippet? [Y/n]: 90 | ``` 91 | 92 | ```bash 93 | ~|⇒ s run curl:ip 94 | ---- 95 | curl canhazip.com 96 | ---- 97 | Execute Snippet? [Y/n]: 98 | ``` 99 | 100 | ### Show snippet 101 | 102 | ```bash 103 | s show [-f ] [-t ] 104 | ``` 105 | 106 | ### List and search snippets 107 | ```bash 108 | s ls [-f ] [-t ] [] 109 | ``` 110 | 111 | * Pattern is matched against snippet name, command and description 112 | 113 | ### List and search snippets for scripts 114 | 115 | * Use the `--porcelain` flag to produce machine-readable output for scripting. 116 | 117 | ```bash 118 | $ s ls service:disable --porcelain 119 | shell service:disable ubuntu disable service on ubuntu 120 | 121 | $ s ls add --porcelain | cut -f 2 | xargs echo 122 | vhost:add user:add alias:add sshconfig:add user:group 123 | ``` 124 | 125 | * The output is `\t`-separated. The colums are: 126 | 1. Snippet file 127 | 2. Snippet name 128 | 3. Tags (`,`-separated) 129 | 4. Description 130 | 131 | ## Fuzzy search file and snippet name: 132 | ```bash 133 | # `r` is alias for `run` 134 | # matches file `mysql` and snippet `database:dump` 135 | 136 | ~|⇒ s r -f sql dmp 137 | ---- 138 | mysqldump -u[user] --lock-tables=[lock] -p[pass] -h [host] [database] > [database].sql 139 | ---- 140 | [user]: 141 | ``` 142 | 143 | ## Config 144 | ```bash 145 | # Append history can be useful to avoid re-entering all placeholders when you need to change single parameter. 146 | export SMAN_APPEND_HISTORY=false 147 | # Snippet directory 148 | export SMAN_SNIPPET_DIR="~/snippets" 149 | # Ask confirmation before executing 150 | export SMAN_EXEC_CONFIRM=true 151 | # Set shell color of groups in ls, see https://misc.flogisoft.com/bash/tip_colors_and_formatting 152 | export SMAN_LS_COLOR_FILES=1,4,35 153 | ``` 154 | 155 | ## vim-sman 156 | 157 | Install vim plugin for better snippets colors: 158 | 159 | * [Pathogen](https://github.com/tpope/vim-pathogen) 160 | * `git clone https://github.com/tokozedg/vim-sman.git ~/.vim/bundle/vim-sman` 161 | * [vim-plug](https://github.com/junegunn/vim-plug) 162 | * `Plug 'tokozedg/vim-sman'` 163 | * [NeoBundle](https://github.com/Shougo/neobundle.vim) 164 | * `NeoBundle 'tokozedg/vim-sman'` 165 | * [Vundle](https://github.com/VundleVim/Vundle.vim) 166 | * `Plugin 'tokozedg/vim-sman'` 167 | 168 | ## Contributing 169 | 170 | If you'd like to contribute, please fork the repository and make changes as 171 | you'd like. Pull requests are warmly welcome, especially if you make a good snippet file. 172 | 173 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #code from junegunn/fzf 4 | 5 | version="v1.0.0" 6 | 7 | download() { 8 | if [ ! -d ~/.sman/ ]; then 9 | if command -v git > /dev/null; then 10 | git clone https://github.com/tokozedg/sman.git ~/.sman/ 11 | else 12 | binary_error="git not found" 13 | return 14 | fi 15 | fi 16 | [ -d ~/.sman/bin ] || mkdir ~/.sman/bin; 17 | cd ~/.sman/bin 18 | local url=https://github.com/tokozedg/sman/releases/download/$version/${1}.tgz 19 | echo $url 20 | if command -v curl > /dev/null; then 21 | curl -fL $url | tar -xz 22 | elif command -v wget > /dev/null; then 23 | wget -O - $url | tar -xz 24 | else 25 | binary_error="curl or wget not found" 26 | return 27 | fi 28 | 29 | if [ ! -f $1 ]; then 30 | binary_error="Failed to download ${url}" 31 | return 32 | fi 33 | 34 | mv ${1} sman; chmod +x sman 35 | } 36 | 37 | 38 | ask() { 39 | # If stdin is a tty, we are "interactive". 40 | # non-interactive shell: wait for a linefeed 41 | # interactive shell: continue after a single keypress 42 | read_n=$([ -t 0 ] && echo "-n 1") 43 | 44 | read -p "$1 ([y]/n) " $read_n -r 45 | echo 46 | [[ $REPLY =~ ^[Nn]$ ]] 47 | } 48 | 49 | append_line() { 50 | set -e 51 | 52 | local update line file pat lno 53 | update="$1" 54 | line="$2" 55 | file="$3" 56 | pat="${4:-}" 57 | 58 | echo "Update $file:" 59 | echo " - $line" 60 | [ -f "$file" ] || touch "$file" 61 | if [ $# -lt 4 ]; then 62 | lno=$(\grep -nF "$line" "$file" | sed 's/:.*//' | tr '\n' ' ') 63 | else 64 | lno=$(\grep -nF "$pat" "$file" | sed 's/:.*//' | tr '\n' ' ') 65 | fi 66 | if [ -n "$lno" ]; then 67 | echo " - Already exists: line #$lno" 68 | else 69 | if [ $update -eq 1 ]; then 70 | echo >> "$file" 71 | echo "$line" >> "$file" 72 | echo " + Added" 73 | else 74 | echo " ~ Skipped" 75 | fi 76 | fi 77 | echo 78 | set +e 79 | } 80 | 81 | # Try to download binary executable 82 | archi=$(uname -sm) 83 | binary_available=1 84 | binary_error="" 85 | case "$archi" in 86 | Darwin\ x86_64) download "sman-darwin-amd64-$version" ;; 87 | Linux\ x86_64) download "sman-linux-amd64-$version" ;; 88 | Linux\ i*86) download "sman-linux-386-$version" ;; 89 | Linux\ arm*) download "sman-linux-arm-$version" ;; 90 | *) binary_available=0 binary_error=1 ;; 91 | esac 92 | 93 | if [ -n "$binary_error" ]; then 94 | if [ $binary_available -eq 0 ]; then 95 | echo "No prebuilt binary for $archi ..." 96 | fi 97 | echo " - $binary_error !!!" 98 | exit 1 99 | fi 100 | 101 | # Append sman.rc to rc 102 | echo 103 | ask "Do you want to update your shell configuration files?" 104 | update_config=$? 105 | has_zsh=$(command -v zsh > /dev/null && echo 1 || echo 0) 106 | shells=$([ $has_zsh -eq 1 ] && echo "bash zsh" || echo "bash") 107 | for shell in $shells; do 108 | [ $shell = zsh ] && dest=${ZDOTDIR:-~}/.zshrc || dest=~/.bashrc 109 | append_line $update_config "[ -f ~/.sman/sman.rc ] && source ~/.sman/sman.rc" "$dest" "~/.sman/sman.rc" 110 | append_line $update_config 'export PATH=$PATH:~/.sman/bin' "$dest" '$PATH:~/.sman/bin' 111 | done 112 | 113 | # Snippets from repo 114 | if [ ! -f ~/snippets/ ]; then 115 | echo 116 | ask "Copy snippets from repo to home?" 117 | if [ $? -eq 1 ]; then 118 | cp -r ~/.sman/snippets ~ 119 | fi 120 | fi 121 | 122 | echo "Done. Logout or reload your rc" 123 | -------------------------------------------------------------------------------- /lib/config.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "github.com/spf13/viper" 5 | "github.com/fatih/color" 6 | ) 7 | 8 | // Config file struct 9 | type Config struct { 10 | SnippetDir string 11 | ExecConfirm, AppendHistory bool 12 | LsFilesColor *color.Color 13 | } 14 | 15 | func init() { 16 | viper.SetDefault("snippet_dir", "~/snippets") 17 | viper.SetDefault("append_history", "true") 18 | viper.SetDefault("exec_confirm", "true") 19 | viper.SetDefault("ls_color_files", "34") 20 | } 21 | 22 | //getConfig reads config and returns struct 23 | func getConfig() (c Config) { 24 | c.SnippetDir = expandPath(viper.GetString("snippet_dir")) 25 | c.AppendHistory = viper.GetBool("append_history") 26 | c.ExecConfirm = viper.GetBool("exec_confirm") 27 | c.LsFilesColor = parseColor(viper.GetString("ls_color_files")) 28 | return c 29 | } 30 | -------------------------------------------------------------------------------- /lib/file.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "gopkg.in/yaml.v2" 5 | "io/ioutil" 6 | "os" 7 | "path/filepath" 8 | "sort" 9 | "strings" 10 | ) 11 | 12 | // baseFileName receives full path and returns file name without extension 13 | func baseFileName(file string) string { 14 | return strings.TrimSuffix(filepath.Base(file), ".yml") 15 | } 16 | 17 | // expandPath receives path string and returns absolute path 18 | // such as expanding ~ to user home path. 19 | func expandPath(p string) string { 20 | p = filepath.Clean(p) 21 | if filepath.IsAbs(p) { 22 | return p 23 | } 24 | if len(p) > 2 && p[:2] == "~/" { 25 | return strings.Replace(p, "~", os.Getenv("HOME"), 1) 26 | } 27 | p, err := filepath.Abs(p) 28 | checkError(err, "Can find absolute path for: "+p) 29 | return p 30 | } 31 | 32 | // ymlFiles returns slice of yml files names in a dir without extension 33 | func ymlFiles(dir string) (files []string) { 34 | fio, _ := ioutil.ReadDir(dir) 35 | for _, f := range fio { 36 | if filepath.Ext(f.Name()) == ".yml" { 37 | n := baseFileName(f.Name()) 38 | files = append(files, n) 39 | } 40 | } 41 | sort.Strings(files) 42 | return files 43 | } 44 | 45 | // unmarshalFile reads yml file and returns snippet objects map 46 | // where snippet name is the map key and Snippet instance is the value 47 | func unmarshalFile(file string) (snippetsMap map[string]Snippet) { 48 | yamlFile, err := ioutil.ReadFile(file) 49 | checkError(err, "Can't read file: "+file) 50 | err = yaml.Unmarshal(yamlFile, &snippetsMap) 51 | checkError(err, "Can't unmarshal file: "+file) 52 | return snippetsMap 53 | } 54 | -------------------------------------------------------------------------------- /lib/file_test.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "reflect" 7 | "testing" 8 | ) 9 | 10 | type file struct { 11 | name, content string 12 | } 13 | 14 | var testFiles = []file{ 15 | 16 | // Valid snippet yml 17 | {"single.yml", 18 | `no_placeholder: 19 | do: copy 20 | tags: 21 | - single 22 | command: test command`}, 23 | {"examples.yml", 24 | `single_placeholder: 25 | do: copy 26 | tags: 27 | - tag1 28 | command: echo <> 29 | multiple_placeholders: 30 | do: copy 31 | tags: 32 | - tag2 33 | command: echo <> <> 34 | ext_command: 35 | do: copy`}, 36 | // Test command file read 37 | {"examples/ext_command", "test command"}, 38 | // Junk file 39 | {"junk", ""}, 40 | } 41 | 42 | const testPath = "./testdata/" 43 | 44 | func makeTestFiles(t *testing.T) { 45 | err := os.MkdirAll(testPath+"/examples", 0770) 46 | if err != nil { 47 | t.Errorf("makeDir: %v", err) 48 | return 49 | } 50 | for _, f := range testFiles { 51 | err := ioutil.WriteFile(testPath+f.name, []byte(f.content), 0644) 52 | if err != nil { 53 | t.Errorf("makeTree: %v", err) 54 | return 55 | } 56 | } 57 | } 58 | 59 | func cleanTestFiles(t *testing.T) { 60 | if err := os.RemoveAll(testPath); err != nil { 61 | t.Errorf("removeTree: %v", err) 62 | } 63 | } 64 | 65 | func TestExpandPath(t *testing.T) { 66 | tests := []struct { 67 | name string 68 | p string 69 | want string 70 | }{ 71 | {"abs path", "/home/user/Documents", "/home/user/Documents"}, 72 | {"home", "~/snippets", os.Getenv("HOME") + "/snippets"}, 73 | {"cleaned", "/home//user/Documents/", "/home/user/Documents"}, 74 | } 75 | for _, tt := range tests { 76 | if got := expandPath(tt.p); got != tt.want { 77 | t.Errorf("%q. expandPath() = %v, want %v", tt.name, got, tt.want) 78 | } 79 | } 80 | } 81 | 82 | func TestYmlFiles(t *testing.T) { 83 | tests := []struct { 84 | name string 85 | dir string 86 | wantFiles []string 87 | }{ 88 | {"valid files", testPath, []string{"examples", "single"}}, 89 | } 90 | makeTestFiles(t) 91 | for _, tt := range tests { 92 | if gotFiles := ymlFiles(tt.dir); !reflect.DeepEqual(gotFiles, tt.wantFiles) { 93 | t.Errorf("%q. ymlFiles() = %v, want %v", tt.name, gotFiles, tt.wantFiles) 94 | } 95 | } 96 | defer cleanTestFiles(t) 97 | } 98 | 99 | func TestUnmarshalFile(t *testing.T) { 100 | tests := []struct { 101 | name string 102 | file string 103 | wantSnippetsMap map[string]Snippet 104 | }{ 105 | {"unmarshal single.yml", testPath + "single.yml", 106 | map[string]Snippet{ 107 | `no_placeholder`: Snippet{ 108 | Command: "test command", 109 | Tags: []string{"single"}, 110 | Do: "copy", 111 | }, 112 | }, 113 | }, 114 | } 115 | makeTestFiles(t) 116 | for _, tt := range tests { 117 | if gotSnippetsMap := unmarshalFile(tt.file); !reflect.DeepEqual(gotSnippetsMap, tt.wantSnippetsMap) { 118 | t.Errorf("%q. unmarshalFile() = %v, want %v", tt.name, gotSnippetsMap, tt.wantSnippetsMap) 119 | } 120 | } 121 | cleanTestFiles(t) 122 | } 123 | -------------------------------------------------------------------------------- /lib/fuzzy.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "github.com/renstrom/fuzzysearch/fuzzy" 5 | "sort" 6 | ) 7 | 8 | // topsFromRanks iterates through fuzzy.Ranks and returns results 9 | // whith the best distance 10 | func topsFromRanks(ranks fuzzy.Ranks) (matched []string) { 11 | if len(ranks) == 0 { 12 | return matched 13 | } 14 | sort.Sort(ranks) 15 | topDistance := ranks[0].Distance 16 | for _, r := range ranks { 17 | if r.Distance == topDistance { 18 | matched = append(matched, r.Target) 19 | } else { 20 | break 21 | } 22 | } 23 | return matched 24 | } 25 | 26 | //fSearchFileName fuzzy searches pattern within available files in a dir 27 | func fSearchFileName(pattern string, dir string) (matched []string) { 28 | files := ymlFiles(dir) 29 | ranks := fuzzy.RankFind(pattern, files) 30 | return topsFromRanks(ranks) 31 | } 32 | 33 | // fSearchSnippet matches pattern to snippet name in SnippetSlice 34 | // returnes SnippetSlice of best matched snippets. 35 | func fSearchSnippet(snippets SnippetSlice, pattern string) (matched SnippetSlice) { 36 | topRank := -1 37 | for _, s := range snippets { 38 | r := fuzzy.RankMatch(pattern, s.Name) 39 | switch { 40 | case r == -1: 41 | continue 42 | case topRank == -1 || r < topRank: 43 | matched = SnippetSlice{s} 44 | topRank = r 45 | case r == topRank: 46 | matched = append(matched, s) 47 | } 48 | } 49 | return matched 50 | } 51 | -------------------------------------------------------------------------------- /lib/fuzzy_test.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "github.com/renstrom/fuzzysearch/fuzzy" 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | func TestTopsFromRanks(t *testing.T) { 10 | tests := []struct { 11 | name string 12 | ranks fuzzy.Ranks 13 | wantMatched []string 14 | }{ 15 | {"empty ranks", 16 | fuzzy.Ranks{}, 17 | []string(nil), 18 | }, 19 | {"single matched", 20 | fuzzy.Ranks{{"fir", "first", 3}, {"fir", "second", 8}}, 21 | []string{"first"}, 22 | }, 23 | {"multiple matched", 24 | fuzzy.Ranks{{"fir", "first", 3}, {"fir", "second", 3}, {"fir", "invalid", 8}}, 25 | []string{"first", "second"}, 26 | }, 27 | } 28 | for _, tt := range tests { 29 | if gotMatched := topsFromRanks(tt.ranks); !reflect.DeepEqual(gotMatched, tt.wantMatched) { 30 | t.Errorf("%q. topsFromRanks() = %v, want %v", tt.name, gotMatched, tt.wantMatched) 31 | } 32 | } 33 | } 34 | 35 | func TestFSearchSnippet(t *testing.T) { 36 | tests := []struct { 37 | name string 38 | snippets SnippetSlice 39 | pattern string 40 | wantMatched SnippetSlice 41 | }{ 42 | {"no match", 43 | SnippetSlice{ 44 | Snippet{Name: "first"}, 45 | Snippet{Name: "nonfirst"}, 46 | }, "bird", 47 | SnippetSlice(nil), 48 | }, 49 | {"single matched", 50 | SnippetSlice{ 51 | Snippet{Name: "first"}, 52 | Snippet{Name: "nonfirst"}, 53 | }, "first", 54 | SnippetSlice{Snippet{Name: "first"}}, 55 | }, 56 | {"multiple matched", 57 | SnippetSlice{ 58 | Snippet{Name: "first"}, 59 | Snippet{Name: "firbe"}, 60 | Snippet{Name: "non:match"}, 61 | }, "fir", 62 | SnippetSlice{ 63 | Snippet{Name: "first"}, 64 | Snippet{Name: "firbe"}, 65 | }, 66 | }, 67 | } 68 | for _, tt := range tests { 69 | if gotMatched := fSearchSnippet(tt.snippets, tt.pattern); !reflect.DeepEqual(gotMatched, tt.wantMatched) { 70 | t.Errorf("%q. fSearchSnippet() = %#v, want %#v", tt.name, gotMatched, tt.wantMatched) 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /lib/ls.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "fmt" 5 | "github.com/spf13/cobra" 6 | "os" 7 | "regexp" 8 | "sort" 9 | "text/tabwriter" 10 | "io" 11 | "strings" 12 | ) 13 | 14 | var ( 15 | porcelainFlag bool 16 | ) 17 | 18 | func filterSnippets(p string, slice SnippetSlice) (matched SnippetSlice) { 19 | r, err := regexp.Compile(p) 20 | checkError(err, "Invalid search pattern") 21 | for _, s := range slice { 22 | if r.MatchString(s.Name) || 23 | r.MatchString(s.Command) || 24 | r.MatchString(s.Desc) { 25 | matched = append(matched, s) 26 | } 27 | } 28 | return matched 29 | } 30 | 31 | func doLs(pattern string) { 32 | c := getConfig() 33 | snippets := getSnippets(pattern, fileFlag, c.SnippetDir, tagFlag) 34 | snippets = filterSnippets(pattern, snippets) 35 | sort.Sort(snippets) 36 | if porcelainFlag { 37 | doLsPorcelain(snippets) 38 | } else { 39 | doLsSlice(snippets, os.Stdout) 40 | } 41 | } 42 | 43 | func doLsSlice(snippets SnippetSlice, output io.Writer) { 44 | c := getConfig() 45 | w := new(tabwriter.Writer) 46 | w.Init(output, 25, 2, 0, ' ', 0) 47 | var prevFile string 48 | for _, s := range snippets { 49 | if s.File != prevFile { 50 | fmt.Fprintln(w, c.LsFilesColor.SprintFunc()(s.File+":")) 51 | prevFile = s.File 52 | } 53 | line := fmt.Sprintf(" %v\t[%v]\t%v", s.Name, displaySlice(s.Tags), 54 | displayString(s.Desc)) 55 | fmt.Fprintln(w, line) 56 | } 57 | err := w.Flush() 58 | checkError(err, "Flush error..") 59 | } 60 | 61 | func doLsPorcelain(snippets SnippetSlice) { 62 | for _, s := range snippets { 63 | fmt.Fprintln(os.Stdout, fmt.Sprintf("%v\t%v\t%v\t%v", s.File, s.Name, strings.Join(s.Tags, ","), s.Desc)) 64 | } 65 | } 66 | 67 | // lsCmd represents the ls command 68 | var lsCmd = &cobra.Command{ 69 | Use: "ls [-f FILE] [-t TAGS] [PATTERN]", 70 | Aliases: []string{"l"}, 71 | Short: "List and search pattern in all available snippets", 72 | Long: ` 73 | List and search pattern in all available snippets, 74 | 75 | PATTERN is regexp matched against snippet name, description and command. 76 | 77 | Examples: 78 | s ls add 79 | - List all snippet matching pattern "add" 80 | s ls -f docker 81 | - List all snippets in file 'docker' 82 | `, 83 | Run: func(cmd *cobra.Command, args []string) { 84 | var p string 85 | if len(args) > 0 { 86 | p = args[0] 87 | } 88 | doLs(p) 89 | }, 90 | } 91 | 92 | func init() { 93 | RootCmd.AddCommand(lsCmd) 94 | lsCmd.Flags().BoolVarP(&porcelainFlag, "porcelain", "", false, "produce machine-readable output") 95 | } 96 | -------------------------------------------------------------------------------- /lib/placeholder.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "strconv" 5 | "strings" 6 | ) 7 | 8 | // Placeholder struct 9 | type Placeholder struct { 10 | Name, Desc, Input string 11 | Options []string 12 | Patterns []string 13 | } 14 | 15 | // DisplayName returns formatted name 16 | func (p *Placeholder) DisplayName() string { 17 | return cyan("[" + p.Name + "]") 18 | } 19 | 20 | // AddPattern adds new pattern to Patterns slice if not exists 21 | func (p *Placeholder) AddPattern(pattern string) { 22 | if !sliceContains(p.Patterns, pattern) { 23 | p.Patterns = append(p.Patterns, pattern) 24 | } 25 | } 26 | 27 | // ParseOptions splits string by comma and sets Options value 28 | func (p *Placeholder) ParseOptions(in string) { 29 | split := strings.Split(in, ",") 30 | // Loop through options, and check for escaped comma 31 | var toAppend string 32 | var op []string 33 | for _, o := range split { 34 | if o[len(o)-1:] == `\` { 35 | toAppend += o[:len(o)-1] 36 | toAppend += "," 37 | continue 38 | } else { 39 | toAppend += o 40 | } 41 | op = append(op, toAppend) 42 | toAppend = "" 43 | } 44 | p.Options = op 45 | } 46 | 47 | // SetInput sets input variable of Placeholder. 48 | // If input is string and Placeholder has options, we try to set option value. 49 | // The same way, if input is empty we try to set first option as input, assuming default value. 50 | func (p *Placeholder) SetInput(input string) { 51 | if len(p.Options) != 0 { 52 | if len(input) == 0 { 53 | input = p.Options[0] 54 | } else if i, err := strconv.Atoi(input); err == nil { 55 | if (i > 0) && (i <= len(p.Options)) { 56 | i-- 57 | input = p.Options[i] 58 | } 59 | } 60 | } 61 | p.Input = input 62 | } 63 | 64 | // searchPlaceholder searches placeholder by name returning position and bool. 65 | func searchPlaceholder(in []Placeholder, n string) (i int, ok bool) { 66 | for i, p := range in { 67 | if p.Name == n { 68 | return i, true 69 | } 70 | } 71 | return i, false 72 | } 73 | -------------------------------------------------------------------------------- /lib/placeholder_test.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestParseOptions(t *testing.T) { 9 | tests := []struct { 10 | name string 11 | in string 12 | wantOptions []string 13 | }{ 14 | {"1", "word", []string{"word"}}, 15 | {"2", "word,bored", []string{"word", "bored"}}, 16 | {"3", `word,\,bored`, []string{"word", ",bored"}}, 17 | {"4", `word,\\,bored`, []string{"word", `\,bored`}}, 18 | } 19 | var p Placeholder 20 | for _, tt := range tests { 21 | p.ParseOptions(tt.in) 22 | if !reflect.DeepEqual(p.Options, tt.wantOptions) { 23 | t.Errorf("%q. ParseOptions() = %v, want %v", tt.name, p.Options, tt.wantOptions) 24 | } 25 | } 26 | } 27 | 28 | func TestPlaceholderSetInput(t *testing.T) { 29 | tests := []struct { 30 | name string 31 | input string 32 | placeholder Placeholder 33 | wantInput string 34 | }{ 35 | {"empty options", "test", Placeholder{}, "test"}, 36 | {"string while has options", "test", 37 | Placeholder{ 38 | Options: []string{"one", "two"}, 39 | }, "test"}, 40 | {"valid option", "1", 41 | Placeholder{ 42 | Options: []string{"one", "two"}, 43 | }, "one"}, 44 | {"number", "3", 45 | Placeholder{ 46 | Options: []string{"one", "two"}, 47 | }, "3"}, 48 | {"empty input", "", 49 | Placeholder{ 50 | Options: []string{"one", "two"}, 51 | }, "one"}, 52 | } 53 | for _, tt := range tests { 54 | tt.placeholder.SetInput(tt.input) 55 | if tt.placeholder.Input != tt.wantInput { 56 | t.Errorf("%q. SetIntput() = %v, want %v", tt.name, tt.placeholder.Input, tt.wantInput) 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /lib/root.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "fmt" 5 | "github.com/fatih/color" 6 | "github.com/spf13/cobra" 7 | "github.com/spf13/viper" 8 | "os" 9 | ) 10 | 11 | var ( 12 | cfgFile, fileFlag, tagFlag string 13 | ) 14 | 15 | const ( 16 | version = "1.0.0" 17 | ) 18 | 19 | //RootCmd for cobra 20 | var RootCmd = &cobra.Command{ 21 | Use: "sman", 22 | Short: "CLI Snippet Manager (" + version + ")", 23 | Long: ``, 24 | } 25 | 26 | //Execute for cobra 27 | func Execute() { 28 | if err := RootCmd.Execute(); err != nil { 29 | fmt.Println(err) 30 | os.Exit(-1) 31 | } 32 | } 33 | 34 | func init() { 35 | cobra.OnInitialize(initConfig) 36 | RootCmd.PersistentFlags().BoolVarP(&color.NoColor, "no-color", "", false, "disable colors") 37 | RootCmd.PersistentFlags().StringVarP(&fileFlag, "file", "f", "", "snippet file") 38 | RootCmd.PersistentFlags().StringVarP(&tagFlag, "tags", "t", "", "tags filter") 39 | } 40 | 41 | func initConfig() { 42 | if cfgFile != "" { 43 | viper.SetConfigFile(cfgFile) 44 | } 45 | viper.SetConfigName(".sman") 46 | viper.AddConfigPath("$HOME") 47 | viper.AutomaticEnv() 48 | viper.SetEnvPrefix("sman") 49 | _ = viper.ReadInConfig() 50 | } 51 | -------------------------------------------------------------------------------- /lib/run.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "fmt" 5 | "github.com/atotto/clipboard" 6 | "github.com/spf13/cobra" 7 | "os" 8 | "strings" 9 | ) 10 | 11 | var ( 12 | copyFlag, execFlag, yesFlag, printFlag bool 13 | ) 14 | 15 | func shellString(s string) string { 16 | return `$'` + s + `'` 17 | } 18 | func appendHistory(snippet Snippet) { 19 | histLine := "s run -f " + snippet.File + " " + snippet.Name 20 | for _, p := range snippet.Placeholders { 21 | if len(p.Input) == 0 { 22 | return 23 | } 24 | histLine += " " + shellString(p.Input) 25 | } 26 | fmt.Println("_append_history ", histLine) 27 | } 28 | 29 | func executeConfirmed() bool { 30 | dashLineError() 31 | msg := "Execute Snippet? [Y/n]: " 32 | for { 33 | printError(msg) 34 | in := readFromCli() 35 | if sliceContains([]string{ 36 | "N", "n", "no", "NO"}, in) { 37 | return false 38 | } else if sliceContains([]string{ 39 | "Y", "y", "yes", "Yes", "YES", ""}, in) { 40 | return true 41 | } 42 | } 43 | } 44 | 45 | func execute(cmd string, confirm bool) { 46 | if confirm && !executeConfirmed() { 47 | return 48 | } 49 | printlnError("Executing...") 50 | fmt.Println(strings.TrimSpace(cmd)) 51 | } 52 | 53 | func requestInput(snippet *Snippet) { 54 | for i := range snippet.Placeholders { 55 | p := &snippet.Placeholders[i] 56 | if len(p.Input) > 0 { 57 | continue 58 | } 59 | if len(p.Desc) > 0 { 60 | printlnError(p.Desc) 61 | } 62 | printError(p.DisplayName()) 63 | if len(p.Options) > 0 { 64 | printError(" ", choicePrompt(p.Options)) 65 | } 66 | printError(": ") 67 | r := readFromCli() 68 | p.SetInput(r) 69 | } 70 | } 71 | 72 | func run(name string, inputs ...string) { 73 | c := getConfig() 74 | snippets := getSnippets(name, fileFlag, c.SnippetDir, tagFlag) 75 | matchedSnippets := fSearchSnippet(snippets, name) 76 | var snippet Snippet 77 | switch len(matchedSnippets) { 78 | case 0: 79 | printlnError("No snippets matched...") 80 | os.Exit(1) 81 | case 1: 82 | snippet = matchedSnippets[0] 83 | default: 84 | printlnError("Multiple snippets matched...") 85 | doLsSlice(matchedSnippets, os.Stderr) 86 | os.Exit(1) 87 | } 88 | 89 | if len(inputs) > len(snippet.Placeholders) { 90 | printlnError("You gave ", len(inputs), " argument(s), limit is ", len(snippet.Placeholders)) 91 | os.Exit(1) 92 | } 93 | 94 | snippet.SetInputs(inputs) 95 | dashLineError() 96 | if len(inputs) < len(snippet.Placeholders) { 97 | printlnError(snippet.DisplayCommand()) 98 | dashLineError() 99 | requestInput(&snippet) 100 | dashLineError() 101 | } 102 | snippet.ReplacePlaceholders() 103 | printlnError(snippet.Command) 104 | dashLineError() 105 | if c.AppendHistory { 106 | appendHistory(snippet) 107 | } 108 | if printFlag { 109 | return 110 | } 111 | if copyFlag || (!execFlag && snippet.Do == "copy") { 112 | err := clipboard.WriteAll(snippet.Command) 113 | checkError(err, "Error while copying") 114 | printlnError("Snippet Copied...") 115 | } 116 | if execFlag || (!copyFlag && snippet.Do == "exec") { 117 | confirmNeeded := !yesFlag && c.ExecConfirm 118 | execute(snippet.Command, confirmNeeded) 119 | } 120 | } 121 | 122 | var runCmd = &cobra.Command{ 123 | Use: "run [-f FILE] [-f TAG] SNIPPET [PLACEHOLDER VALUES...] [-cxyp]", 124 | Aliases: []string{"r"}, 125 | Short: "Run snippet", 126 | Long: ` 127 | Runs snippet and execute action specified with flags or snippet "do". 128 | Flags action overrides "do". 129 | 130 | The next arguments after snippet name will be used to fill placeholder values. 131 | The first argument will be considered as a first placeholder input. 132 | Use "s show " to get placeholder order numbers. 133 | 134 | Examples: 135 | s run -f mysql db:dump -x 136 | - run 'db:dump' snippet from file 'mysql' and execute when done 137 | `, 138 | Run: func(cmd *cobra.Command, args []string) { 139 | if len(args) == 0 { 140 | printlnError("need snippet name...") 141 | os.Exit(1) 142 | } 143 | run(args[0], args[1:]...) 144 | }, 145 | } 146 | 147 | func init() { 148 | RootCmd.AddCommand(runCmd) 149 | RootCmd.SetOutput(os.Stderr) 150 | runCmd.Flags().BoolVarP(©Flag, "copy", "c", false, "copy snippet") 151 | runCmd.Flags().BoolVarP(&execFlag, "exec", "x", false, "execute snippet") 152 | runCmd.Flags().BoolVarP(&yesFlag, "yes", "y", false, "skip confirmation when executing") 153 | runCmd.Flags().BoolVarP(&printFlag, "print", "p", false, "print snippet") 154 | } 155 | -------------------------------------------------------------------------------- /lib/show.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "fmt" 5 | "github.com/spf13/cobra" 6 | "os" 7 | "sort" 8 | "strings" 9 | "text/tabwriter" 10 | ) 11 | 12 | func showSnippets(slice SnippetSlice) { 13 | w := new(tabwriter.Writer) 14 | w.Init(os.Stdout, 0, 4, 2, ' ', 0) 15 | sort.Sort(slice) 16 | for _, s := range slice { 17 | fmt.Fprintln(w, magenta(s.File)) 18 | dashLine() 19 | fmt.Fprintln(w, "\tName:\t"+s.Name) 20 | fmt.Fprintln(w, "\tDesc:\t"+displayString(s.Desc)) 21 | fmt.Fprintln(w, "\tTags:\t"+displaySlice(s.Tags)) 22 | fmt.Fprintln(w, "\tDo:\t"+displayString(s.Do)) 23 | fmt.Fprintln(w, "\tCommand:\t") 24 | fmt.Fprintln(w) 25 | for _, l := range strings.Split(s.DisplayCommand(), "\n") { 26 | fmt.Fprintln(w, "\t ", l) 27 | } 28 | fmt.Fprintln(w) 29 | for i, p := range s.Placeholders { 30 | i++ 31 | n := fmt.Sprintf("\t\t\t[%v] %s", i, p.DisplayName()) 32 | fmt.Fprintln(w, n) 33 | fmt.Fprintln(w, "\t\t\t\t\tOptions:\t"+displaySlice(p.Options)) 34 | fmt.Fprintln(w, "\t\t\t\t\tDesc:\t"+displayString(p.Desc)) 35 | } 36 | } 37 | err := w.Flush() 38 | checkError(err, "Flush error...") 39 | } 40 | 41 | func show(name string) { 42 | c := getConfig() 43 | snippets := getSnippets(name, fileFlag, c.SnippetDir, tagFlag) 44 | matchedSnippets := fSearchSnippet(snippets, name) 45 | showSnippets(matchedSnippets) 46 | } 47 | 48 | var showCmd = &cobra.Command{ 49 | Use: "show [-f FILE] [-t TAG] SNIPPET", 50 | Aliases: []string{"s"}, 51 | Short: "Show snippet details", 52 | Long: ` 53 | Show snippet details. 54 | 55 | Examples: 56 | s show alias:add -t shell 57 | 58 | `, 59 | Run: func(cmd *cobra.Command, args []string) { 60 | if len(args) == 0 { 61 | fmt.Println("need snippet name...") 62 | os.Exit(1) 63 | } 64 | show(args[0]) 65 | }, 66 | } 67 | 68 | func init() { 69 | RootCmd.AddCommand(showCmd) 70 | } 71 | -------------------------------------------------------------------------------- /lib/snippet.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "regexp" 7 | "strings" 8 | ) 9 | 10 | // Snippet struct 11 | type Snippet struct { 12 | Desc, Command, Name, Do, File string 13 | Tags []string 14 | Placeholders []Placeholder 15 | } 16 | 17 | // DisplayCommand returns formatted command 18 | func (s *Snippet) DisplayCommand() (out string) { 19 | out = s.Command 20 | for _, p := range s.Placeholders { 21 | for _, t := range p.Patterns { 22 | out = strings.Replace(out, t, 23 | p.DisplayName(), -1) 24 | } 25 | } 26 | out = strings.TrimSpace(out) 27 | return out 28 | } 29 | 30 | // SetInputs receives slice of inputs and sets Placeholders inputs in the same order 31 | func (s *Snippet) SetInputs(inputs []string) { 32 | for i, v := range inputs { 33 | if i > len(s.Placeholders) { 34 | return 35 | } 36 | s.Placeholders[i].SetInput(v) 37 | } 38 | } 39 | 40 | // ReplacePlaceholders replaces placeholders patterns by placeholders input 41 | func (s *Snippet) ReplacePlaceholders() { 42 | for _, p := range s.Placeholders { 43 | for _, pattern := range p.Patterns { 44 | s.Command = strings.Replace(s.Command, pattern, p.Input, -1) 45 | } 46 | } 47 | } 48 | 49 | // ParseCommand reads snippet command and creates Placeholders instance 50 | func (s *Snippet) ParseCommand() { 51 | r, err := regexp.Compile(`<<(\w+)(?:\((.*?)\))?(#.*?)?>>`) 52 | checkError(err, "Invalid regexp") 53 | m := r.FindAllStringSubmatch(s.Command, -1) 54 | for _, v := range m { 55 | pattern := v[0] 56 | name := v[1] 57 | options := v[2] 58 | desc := v[3] 59 | // If placeholder already exists 60 | if i, ok := searchPlaceholder(s.Placeholders, name); ok { 61 | s.Placeholders[i].AddPattern(pattern) 62 | } else { 63 | // Create new placeholder 64 | var p Placeholder 65 | p.Name = name 66 | p.Desc = desc 67 | if len(options) > 0 { 68 | p.ParseOptions(options) 69 | } 70 | p.AddPattern(pattern) 71 | s.Placeholders = append(s.Placeholders, p) 72 | } 73 | } 74 | } 75 | 76 | // initSnippets initializes snippet after unmarshal 77 | func initSnippets(snippetMap map[string]Snippet, file string, dir string) (snippets SnippetSlice) { 78 | for n, s := range snippetMap { 79 | s.Name = n 80 | s.File = file 81 | if len(s.Command) == 0 { 82 | // Search command file 83 | c, _ := ioutil.ReadFile(dir + "/" + s.File + "/" + s.Name) 84 | if len(c) > 0 { 85 | s.Command = strings.TrimSpace(string(c)) 86 | } else { 87 | continue 88 | } 89 | } 90 | s.ParseCommand() 91 | snippets = append(snippets, s) 92 | } 93 | return snippets 94 | } 95 | 96 | // filterByTag filters snippet slice by tag 97 | func filterByTag(snippets SnippetSlice, tag string) (matched SnippetSlice) { 98 | for _, s := range snippets { 99 | if sliceContains(s.Tags, tag) { 100 | matched = append(matched, s) 101 | } 102 | } 103 | return matched 104 | } 105 | 106 | // snippetsInFile returns snippet slice in file 107 | func snippetsInFile(file, dir string) (snippets SnippetSlice) { 108 | fullPath := dir + "/" + file + ".yml" 109 | snippets = initSnippets(unmarshalFile(fullPath), file, dir) 110 | return snippets 111 | } 112 | 113 | // snippetsInDir returns snippet in dir 114 | func snippetsInDir(dir string) (snippets SnippetSlice) { 115 | for _, f := range ymlFiles(dir) { 116 | snippets = append(snippets, snippetsInFile(f, dir)...) 117 | } 118 | return snippets 119 | } 120 | 121 | func getSnippets(name, file, dir, tag string) SnippetSlice { 122 | var snippets SnippetSlice 123 | // file flag is defined. Use fuzzy search 124 | if len(file) > 0 { 125 | fileMatched := fSearchFileName(file, dir) 126 | switch len(fileMatched) { 127 | case 0: 128 | printlnError("Unable to find any file with pattern: " + file) 129 | os.Exit(1) 130 | case 1: 131 | snippets = snippetsInFile(fileMatched[0], dir) 132 | default: 133 | printError("Multiple files matched.") 134 | os.Exit(1) 135 | } 136 | } else { 137 | snippets = snippetsInDir(dir) 138 | } 139 | // filter snippets by tag 140 | if len(tag) > 0 { 141 | return filterByTag(snippets, tag) 142 | } 143 | return snippets 144 | } 145 | 146 | // SnippetSlice for sorting 147 | type SnippetSlice []Snippet 148 | 149 | func (s SnippetSlice) Len() int { 150 | return len(s) 151 | } 152 | 153 | func (s SnippetSlice) Less(a, b int) bool { 154 | return s[a].File+s[a].Name < s[b].File+s[b].Name 155 | } 156 | 157 | func (s SnippetSlice) Swap(a, b int) { 158 | s[a], s[b] = s[b], s[a] 159 | } 160 | -------------------------------------------------------------------------------- /lib/snippet_test.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestSnippetReplacePlaceholders(t *testing.T) { 9 | tests := []struct { 10 | name string 11 | command string 12 | placeholders []Placeholder 13 | wantCommand string 14 | }{ 15 | {"no placeholder", "hello world", []Placeholder(nil), "hello world"}, 16 | {"single patterns", "hello <>", 17 | []Placeholder{ 18 | Placeholder{ 19 | Name: "name", 20 | Patterns: []string{"<>"}, 21 | Input: "test", 22 | }, 23 | }, 24 | "hello test", 25 | }, 26 | {"multiple patterns", "hello <> sup <>", 27 | []Placeholder{ 28 | Placeholder{ 29 | Name: "name", 30 | Patterns: []string{"<>", "<>"}, 31 | Input: "test", 32 | }, 33 | }, 34 | "hello test sup test", 35 | }, 36 | } 37 | for _, tt := range tests { 38 | s := &Snippet{ 39 | Command: tt.command, 40 | Placeholders: tt.placeholders, 41 | } 42 | s.ReplacePlaceholders() 43 | if s.Command != tt.wantCommand { 44 | t.Errorf("%q. ReplacePlaceholders() = %#v, want %#v", tt.name, s.Command, tt.wantCommand) 45 | } 46 | } 47 | } 48 | 49 | func TestSnippetParseCommand(t *testing.T) { 50 | tests := []struct { 51 | name string 52 | command string 53 | wantPlaceholders []Placeholder 54 | }{ 55 | {"no placeholder", "hello world", []Placeholder(nil)}, 56 | {"full placeholder", "hello <>", 57 | []Placeholder{ 58 | Placeholder{ 59 | Name: "name", 60 | Desc: "#desc", 61 | Options: []string{"one", "two"}, 62 | Patterns: []string{"<>"}, 63 | }, 64 | }, 65 | }, 66 | {"multiple patterns", `hello <> <>`, 67 | []Placeholder{ 68 | Placeholder{ 69 | Name: "name", 70 | Desc: "#desc", 71 | Patterns: []string{"<>", "<>"}, 72 | }, 73 | }, 74 | }, 75 | {"multiple placeholders", `hello <> <>`, 76 | []Placeholder{ 77 | Placeholder{ 78 | Name: "name", 79 | Patterns: []string{"<>"}, 80 | }, 81 | Placeholder{ 82 | Name: "last", 83 | Patterns: []string{"<>"}, 84 | }, 85 | }, 86 | }, 87 | } 88 | for _, tt := range tests { 89 | s := &Snippet{ 90 | Command: tt.command, 91 | } 92 | s.ParseCommand() 93 | if !reflect.DeepEqual(s.Placeholders, tt.wantPlaceholders) { 94 | t.Errorf("%q. ParseCommand() = %#v, want %#v", tt.name, s.Placeholders, tt.wantPlaceholders) 95 | } 96 | } 97 | } 98 | 99 | func TestInitSnippets(t *testing.T) { 100 | tests := []struct { 101 | name string 102 | snippetMap map[string]Snippet 103 | file string 104 | dir string 105 | wantSnippets SnippetSlice 106 | }{ 107 | {"t", 108 | map[string]Snippet{"echo": Snippet{Command: "hello world"}}, 109 | "file", "", 110 | SnippetSlice{ 111 | Snippet{ 112 | Name: "echo", 113 | Command: "hello world", 114 | File: "file", 115 | }, 116 | }, 117 | }, 118 | {"ext_command", 119 | map[string]Snippet{"ext_command": Snippet{}}, 120 | "examples", testPath, 121 | SnippetSlice{ 122 | Snippet{ 123 | Name: "ext_command", 124 | Command: "test command", 125 | File: "examples", 126 | }, 127 | }, 128 | }, 129 | {"invalid snippet", 130 | map[string]Snippet{"invalid_snippet": Snippet{}}, 131 | "examples", testPath, 132 | SnippetSlice(nil), 133 | }, 134 | } 135 | makeTestFiles(t) 136 | for _, tt := range tests { 137 | if gotSnippets := initSnippets(tt.snippetMap, tt.file, tt.dir); !reflect.DeepEqual(gotSnippets, tt.wantSnippets) { 138 | t.Errorf("%q. initSnippets() = %#v, want %#v", tt.name, gotSnippets, tt.wantSnippets) 139 | } 140 | } 141 | defer cleanTestFiles(t) 142 | } 143 | 144 | func TestFilterByTag(t *testing.T) { 145 | tests := []struct { 146 | name string 147 | snippets SnippetSlice 148 | tag string 149 | wantMatched SnippetSlice 150 | }{ 151 | {"1", 152 | SnippetSlice{ 153 | Snippet{ 154 | Name: "skipped", 155 | }, 156 | Snippet{ 157 | Name: "matched", 158 | Tags: []string{"tag"}, 159 | }, 160 | }, 161 | "tag", 162 | SnippetSlice{ 163 | Snippet{ 164 | Name: "matched", 165 | Tags: []string{"tag"}, 166 | }, 167 | }, 168 | }, 169 | } 170 | for _, tt := range tests { 171 | if gotMatched := filterByTag(tt.snippets, tt.tag); !reflect.DeepEqual(gotMatched, tt.wantMatched) { 172 | t.Errorf("%q. filterByTag() = %v, want %v", tt.name, gotMatched, tt.wantMatched) 173 | } 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /lib/utils.go: -------------------------------------------------------------------------------- 1 | package sman 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "github.com/fatih/color" 7 | "os" 8 | "strings" 9 | "strconv" 10 | ) 11 | 12 | // readFromCli reads CLI input and return string 13 | func readFromCli() string { 14 | reader := bufio.NewReader(os.Stdin) 15 | i, _ := reader.ReadString('\n') 16 | i = strings.TrimSpace(i) 17 | return i 18 | } 19 | 20 | func printError(line ...interface{}) { 21 | for _, l := range line { 22 | s := fmt.Sprint(l) 23 | _, _ = os.Stderr.WriteString(s) 24 | } 25 | } 26 | 27 | func printlnError(line ...interface{}) { 28 | printError(line...) 29 | printError("\n") 30 | } 31 | 32 | func dashLineError() { 33 | printlnError("----") 34 | } 35 | 36 | func dashLine() { 37 | fmt.Println("----") 38 | } 39 | 40 | // displayString titles string or returns dashes if empty 41 | func displayString(s string) string { 42 | if len(s) > 0 { 43 | return strings.Title(s) 44 | } 45 | return "----" 46 | } 47 | 48 | // displaySlice joins slice and returns titled string or dashes if empty 49 | func displaySlice(s []string) string { 50 | return displayString(strings.Join(s, " | ")) 51 | } 52 | 53 | func magenta(s string) string { 54 | m := color.New(color.FgMagenta).SprintFunc() 55 | return m(s) 56 | } 57 | 58 | func cyan(s string) string { 59 | c := color.New(color.FgCyan).SprintFunc() 60 | return c(s) 61 | } 62 | 63 | // convert a comma-separated string to color 64 | func parseColor(strValue string) *color.Color { 65 | returnColor := color.New() 66 | colorArray := strings.Split(strValue, ",") 67 | for _, part := range colorArray { 68 | integer, err := strconv.Atoi(part) 69 | if err != nil { 70 | printError("Error setting color: ") 71 | printlnError(err) 72 | } else { 73 | returnColor.Add(color.Attribute(integer)); 74 | } 75 | } 76 | return returnColor 77 | } 78 | 79 | func choicePrompt(from []string) (result string) { 80 | for i, s := range from { 81 | i++ 82 | var bs, be, sp string 83 | if i == 1 { 84 | bs = "[" 85 | be = "]" 86 | } else { 87 | bs = "(" 88 | be = ")" 89 | } 90 | if i != len(from) { 91 | sp = " " 92 | } 93 | result += fmt.Sprintf("%s%v%s %s%s", bs, i, be, s, sp) 94 | } 95 | return result 96 | } 97 | 98 | func checkError(e error, msg string) { 99 | if e != nil { 100 | printlnError(msg) 101 | panic(e) 102 | } 103 | } 104 | 105 | // sliceContains checks if string exists in slice 106 | func sliceContains(in []string, dst string) bool { 107 | for _, i := range in { 108 | if i == dst { 109 | return true 110 | } 111 | } 112 | return false 113 | } 114 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/tokozedg/sman/lib" 5 | ) 6 | 7 | func main() { 8 | sman.RootCmd.Execute() 9 | } 10 | -------------------------------------------------------------------------------- /sman.rc: -------------------------------------------------------------------------------- 1 | # vim: set ft=sh: 2 | 3 | s() { 4 | if [[ ${1} == "run" ]] || [[ ${1} == "r" ]]; then 5 | eval "$(sman "$@")" 6 | else 7 | sman "$@" 8 | fi 9 | } 10 | 11 | _escaped_string(){ 12 | if [[ "$1" =~ ^[-:_[:alnum:]]*$ ]]; 13 | then 14 | echo "$1" 15 | elif [[ "$1" =~ ^[^\']*$ ]]; 16 | then 17 | echo "'$1'" 18 | else 19 | echo "\"$1\"" 20 | fi 21 | } 22 | 23 | 24 | _history_command(){ 25 | if [[ ! -z $BASH_VERSION ]]; 26 | then 27 | echo "history -s" 28 | elif [[ ! -z $ZSH_VERSION ]]; 29 | then 30 | echo "print -s" 31 | fi 32 | 33 | } 34 | 35 | _append_history(){ 36 | local command 37 | for arg; do 38 | local output=$(_escaped_string "$arg") 39 | if [[ ! -z $command ]]; 40 | then 41 | command="$command $output" 42 | else 43 | command="$output" 44 | fi 45 | done 46 | $(_history_command) "$command" 47 | } 48 | -------------------------------------------------------------------------------- /snippets/.gitignore: -------------------------------------------------------------------------------- 1 | *4s.yml 2 | toko.yml 3 | -------------------------------------------------------------------------------- /snippets/apache.yml: -------------------------------------------------------------------------------- 1 | --- 2 | vhost:add: 3 | do: copy 4 | desc: create new vhost 5 | -------------------------------------------------------------------------------- /snippets/apache/vhost:add: -------------------------------------------------------------------------------- 1 | 2 | ServerAdmin admin@<> 3 | ServerName <> 4 | ServerAlias www.<> 5 | DocumentRoot /var/www/<>/ 6 | ErrorLog ${APACHE_LOG_DIR}/error.<>.log 7 | CustomLog ${APACHE_LOG_DIR}/access.<>.log combined 8 | 9 | -------------------------------------------------------------------------------- /snippets/aptitude.yml: -------------------------------------------------------------------------------- 1 | --- 2 | aptitude:hold: 3 | do: exec 4 | desc: Hold package at the current version 5 | command: sudo apt-mark hold <> 6 | aptitude:install: 7 | do: exec 8 | desc: install a specific version of a package 9 | command: sudo aptitude install <>=<> 10 | aptitude:release: 11 | do: exec 12 | desc: Release hold on a package 13 | command: sudo apt-mark unhold <> 14 | aptitude:search: 15 | do: exec 16 | desc: search for a package 17 | command: aptitude search <> 18 | aptitude:show: 19 | do: exec 20 | desc: show package information 21 | command: aptitude show <> 22 | aptitude:update: 23 | do: exec 24 | desc: Update local package database 25 | command: sudo aptitude update 26 | aptitude:upgrade: 27 | do: exec 28 | desc: Update packages 29 | command: sudo aptitude upgrade 30 | aptitude:versions: 31 | do: exec 32 | desc: show available versions of a package 33 | command: sudo aptitude versions <> 34 | -------------------------------------------------------------------------------- /snippets/docker.yml: -------------------------------------------------------------------------------- 1 | --- 2 | attach: 3 | do: exec 4 | desc: attach without sig-proxy 5 | command: docker attach --sig-proxy=false <> 6 | rm: 7 | do: exec 8 | desc: stop and remove single or all containers 9 | command: docker stop <>; docker rm <> 10 | inspect: 11 | do: exec 12 | desc: inspect ip/ports 13 | command: >- 14 | docker inspect --format "{{ .Name }} # {{ .NetworkSettings.IPAddress }} 15 | # {{ .NetworkSettings.Ports }}" $(docker ps -q) | tr -s '#' '\t' | column -t 16 | stop: 17 | do: exec 18 | desc: stop single or all containers 19 | command: docker stop <>; 20 | bash: 21 | do: exec 22 | desc: run bash in container 23 | command: docker exec -it <> bash 24 | -------------------------------------------------------------------------------- /snippets/elastic.yml: -------------------------------------------------------------------------------- 1 | --- 2 | index:delete: 3 | do: exec 4 | desc: delete index on elasticsearch 5 | command: curl -XDELETE 'http://<>/<>/' 6 | -------------------------------------------------------------------------------- /snippets/github.yml: -------------------------------------------------------------------------------- 1 | --- 2 | oh-my-zsh: 3 | do: copy 4 | desc: install oh-my-zsh 5 | command: | 6 | sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" 7 | fzf: 8 | do: copy 9 | desc: install fzf 10 | command: | 11 | git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf; 12 | ~/.fzf/install 13 | sman: 14 | do: copy 15 | desc: install sman 16 | command: | 17 | sh -c "$(curl https://raw.githubusercontent.com/tokozedg/sman/master/install.sh)" 18 | -------------------------------------------------------------------------------- /snippets/go.yml: -------------------------------------------------------------------------------- 1 | cover:html: 2 | do: exec 3 | desc: generate html report of test cover 4 | command: | 5 | go test -coverprofile=cover.out; 6 | go tool cover -html=cover.out 7 | -------------------------------------------------------------------------------- /snippets/mysql.yml: -------------------------------------------------------------------------------- 1 | --- 2 | user:add: 3 | do: copy 4 | desc: create user for database 5 | command: >- 6 | GRANT <> ON 7 | <>.* TO <>@'<>' IDENTIFIED BY '<>'; 8 | FLUSH PRIVILEGES; 9 | database:dump: 10 | do: copy 11 | desc: dump database to file 12 | command: >- 13 | mysqldump -u<> --lock-tables=<> 14 | -p<> -h <> <> > <>.sql 15 | ngrep:query: 16 | do: copy 17 | desc: ngrep mysql queries (non socket only) 18 | command: | 19 | ngrep -d <> -i '<>' port 3306 20 | -------------------------------------------------------------------------------- /snippets/postgresql.yml: -------------------------------------------------------------------------------- 1 | --- 2 | postgresql:watch: 3 | do: copy 4 | desc: postgresql version of mysqladmin -i 2 proc 5 | command: watch \"psql -P pager -c 'select datname,pid,usename,waiting,state,query from pg_stat_activity;' tasks\" 6 | -------------------------------------------------------------------------------- /snippets/puppet.yml: -------------------------------------------------------------------------------- 1 | --- 2 | node:remove: 3 | do: copy 4 | desc: remove node from puppet master 5 | tags: 6 | - enterprise 7 | command: | 8 | puppet node purge <>; 9 | puppet agent -t; 10 | service pe-puppetserver restart 11 | gem:install: 12 | do: copy 13 | desc: install gem for puppetmaster 14 | tags: 15 | - enterprise 16 | command: | 17 | /opt/puppet/bin/puppetserver gem install <>; 18 | service pe-puppetserver restart 19 | module:install: 20 | do: copy 21 | desc: install new module 22 | command: | 23 | puppet module install --environment <> <> 24 | epp:validate: 25 | do: copy 26 | desc: check syntax of EPP code 27 | command: puppet epp validate <> 28 | erb:validate: 29 | do: exec 30 | desc: check syntax of ERB code 31 | command: erb -P -x -T '-' <> | ruby -c 32 | -------------------------------------------------------------------------------- /snippets/shell.yml: -------------------------------------------------------------------------------- 1 | --- 2 | alias:add: 3 | do: exec 4 | desc: add alias and reload rc 5 | command: >- 6 | echo "alias <>='<>'" >> 7 | ~/.bash_aliases; source ~/.bash_aliases 8 | user:group: 9 | do: exec 10 | desc: add user to group 11 | command: usermod -a -G <> <> 12 | curl:upload: 13 | do: exec 14 | desc: encrypt file and upload to transfer.sh 15 | command: | 16 | gpg -c <>; 17 | curl --upload-file <>.gpg https://transfer.sh/<>.gpg 18 | curl:ip: 19 | do: exec 20 | desc: my external ip 21 | command: curl canhazip.com 22 | sshconfig:add: 23 | do: exec 24 | desc: add new machine to ssh config 25 | mount:ram: 26 | do: copy 27 | desc: mount ram as file system 28 | command: mount -t ramfs -o size=<>G ramfs <> 29 | tcpdump:port: 30 | do: exec 31 | desc: listen traffic on port 32 | command: | 33 | tcpdump -nqt -s 0 -A -i eth0 port <> 34 | ngrep:port: 35 | do: exec 36 | desc: ngrep to port 37 | command: ngrep -W byline -d eth0 <> 38 | sed:replace: 39 | do: exec 40 | desc: replace string in all files 41 | command: | 42 | sed -i 's/<>/<>/g' *.<> 43 | smtp:server: 44 | do: exec 45 | desc: smtp server in python. Prints mails to stdout 46 | command: | 47 | python -m smtpd -n -c DebuggingServer localhost:1025 48 | tar:file: 49 | do: exec 50 | desc: create a gzipped archive 51 | command: tar czvf <>.tar.gz <> 52 | service:disable: 53 | do: copy 54 | desc: disable service on ubuntu 55 | tags: 56 | - ubuntu 57 | command: sudo update-rc.d <> disable 58 | service:status: 59 | do: copy 60 | desc: list all services 61 | tags: 62 | - centos 63 | command: systemctl -t service 64 | for:file: 65 | do: exec 66 | desc: recursive for file loop 67 | -------------------------------------------------------------------------------- /snippets/shell/for:file: -------------------------------------------------------------------------------- 1 | for f in $(find . -name "*.<>"); 2 | do 3 | <>; 4 | done 5 | -------------------------------------------------------------------------------- /snippets/shell/sshconfig:add: -------------------------------------------------------------------------------- 1 | ssh-copy-id <>@<>; 2 | if ! grep -Fxq "Host <>" ~/.ssh/config; 3 | then 4 | echo "Host <> 5 | HostName <> 6 | Port 22 7 | User <>" >> ~/.ssh/config; 8 | fi 9 | 10 | -------------------------------------------------------------------------------- /snippets/ufw.yml: -------------------------------------------------------------------------------- 1 | --- 2 | ufw:allow: 3 | do: exec 4 | desc: open port in ufw 5 | command: sudo ufw allow proto <> from <> to any port <> 6 | ufw:deny: 7 | do: exec 8 | desc: drop IP in ufw 9 | command: sudo ufw deny <> from <> 10 | 11 | -------------------------------------------------------------------------------- /snippets/varnish.yml: -------------------------------------------------------------------------------- 1 | --- 2 | vcl:validate: 3 | do: copy 4 | desc: check VCL syntax 5 | command: varnishd -C -f <> 6 | -------------------------------------------------------------------------------- /snippets/vbox.yml: -------------------------------------------------------------------------------- 1 | --- 2 | vm:start: 3 | do: exec 4 | desc: start virtualbox machine 5 | command: VBoxManage startvm '<>' --type headless 6 | 7 | --------------------------------------------------------------------------------