├── .gitignore ├── .goreleaser.yaml ├── LICENSE ├── README.md ├── cmd ├── deploy │ └── deploy.go ├── destroy.go ├── init.go ├── launch │ └── launch.go ├── preview │ ├── list │ │ └── list.go │ ├── preview.go │ └── remove │ │ └── remove.go └── root.go ├── demo └── imgs │ ├── deploy.png │ ├── hero.png │ ├── init.png │ ├── launch.png │ └── preview.png ├── go.mod ├── go.sum ├── main.go ├── render ├── tui.go ├── types.go └── utils.go └── utils ├── auth.go ├── scripts.go ├── spinner.go ├── stages.go ├── types.go ├── utils.go └── utils_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | dist/ 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /.goreleaser.yaml: -------------------------------------------------------------------------------- 1 | # This is an example .goreleaser.yml file with some sensible defaults. 2 | # Make sure to check the documentation at https://goreleaser.com 3 | 4 | # The lines below are called `modelines`. See `:help modeline` 5 | # Feel free to remove those if you don't want/need to use them. 6 | # yaml-language-server: $schema=https://goreleaser.com/static/schema.json 7 | # vim: set ts=2 sw=2 tw=0 fo=cnqoj 8 | 9 | version: 2 10 | 11 | before: 12 | hooks: 13 | # You may remove this if you don't use go modules. 14 | - go mod tidy 15 | 16 | builds: 17 | - env: 18 | - CGO_ENABLED=0 19 | ldflags: 20 | - "-X 'github.com/mightymoud/sidekick/cmd.version={{.Tag}}'" 21 | goos: 22 | - linux 23 | - windows 24 | - darwin 25 | 26 | archives: 27 | - format: tar.gz 28 | # this name template makes the OS and Arch compatible with the results of `uname`. 29 | name_template: >- 30 | {{ .ProjectName }}_ 31 | {{- title .Os }}_ 32 | {{- if eq .Arch "amd64" }}x86_64 33 | {{- else if eq .Arch "386" }}i386 34 | {{- else }}{{ .Arch }}{{ end }} 35 | {{- if .Arm }}v{{ .Arm }}{{ end }} 36 | # use zip for windows archives 37 | format_overrides: 38 | - goos: windows 39 | format: zip 40 | 41 | changelog: 42 | sort: asc 43 | filters: 44 | exclude: 45 | - "^docs:" 46 | - "^test:" 47 | - "^chore:" 48 | 49 | release: 50 | draft: true 51 | 52 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 | 5 |
6 | 7 | Bare metal to production ready in mins; imagine fly.io on your VPS 8 | 9 |
10 | 11 |
12 | 13 | ![GitHub](https://img.shields.io/github/license/mightymoud/sidekick) 14 | ![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/mightymoud/sidekick) 15 | ![GitHub tag (latest SemVer)](https://img.shields.io/github/v/tag/mightymoud/sidekick) 16 | 17 |
18 | 19 | ## Features 20 | 21 | - 👍 One command VPS setup (docker, traefik, sops, age) 22 | - 💻 deploy any application from a dockerfile 23 | - ✊ Zero downtime deployment 24 | - 🌏 High availability and load balancing 25 | - 🔒 Zero config SSL Certs 26 | - ✅ Connect domains or use sslip.io out of the box 27 | - 🔥 Built in integration with SOPS 28 | - 🛸 Escape the vendorlock forever 29 | 30 | ## Motivation 31 | 32 | I'm tired of the complexity involved in hosting my side projects. While some platforms, like Fly.io, stand out in the crowded field of Heroku replacements, I believe a simple VPS can be just as effective. That's why I created Sidekick: to make hosting side projects as straightforward, affordable, and production-ready as possible. You'll be surprised how much traffic a $8/month instance on DigitalOcean can handle. 33 | 34 | ## Installation 35 | 36 | Using brew: 37 | 38 | ```bash 39 | brew install sidekick 40 | ``` 41 | 42 | NOTE: Sidekick uses `brew` later on to handle installing `sops` on your local. So `brew` is a requirement at this point. Sidekick will throw an error if `brew` is not found. You can install `brew` from [here](https://brew.sh/). 43 | 44 | ## Usage 45 | 46 | Sidekick helps you along all the steps of deployment on your VPS. From basic setup to zero downtime deploys, we got you! ✊ 47 | 48 | First you need a VPS with Ubuntu LTS. I recommend DigitalOcean. Hetzner also gets very good reviews. You can host your own silicon too. As long as you have a public IP address you can use Sidekick. 49 | 50 | Just make sure the following is true: 51 | 52 | - VPS running Ubuntu - LTS recommended 53 | - SSH Key available on your machine to login to VPS. 54 | 55 | That's it! 56 | 57 | ### VPS Setup 58 | 59 |
60 | 61 |
62 | 63 | First you need to setup your VPS. To do this you need to run: 64 | 65 | ```bash 66 | sidekick init 67 | ``` 68 | 69 | Then you need to enter the following: 70 | 71 | - IP Address of your VPS 72 | - An email address to use for setting up SSL certs 73 | 74 | After that Sidekick will setup many things on your VPS - Usually takes around 2 mins. 75 | If you run this command once more and enter a different IP Address, Sidekick will warn you that you are overriding the current config with a prompt. 76 | 77 | You can use flags instead. Read more [in the docs](https://www.sidekickdeploy.com/docs/command/init/). 78 | 79 |
80 | What does Sidekick do when I run this command? 81 | 82 | * Login with `root` user 83 | * Make a new user `sidekick` and grant sudo access 84 | * Logout from `root` and login with `sidekick` 85 | * Disable login with `root` user - security best practice 86 | * Update and upgrade your Ubuntu system 87 | * Install `sops` and copy over the public key to your sidekick config file 88 | * Use `age` to make secret and public keys to use later for encrypting env file. 89 | * Send public key back to host machine to be used later for encryption 90 | * Install Docker 91 | * Add user sidekick to docker group 92 | * Setup Traefik and SSL certs on your VPS 93 |
94 | 95 |
96 | Which SSH key will Sidekick use to login? 97 | 98 | Sidekick will look up the default keys in your default .ssh directory in the following order: 99 | 100 | - id_rsa.pub 101 | - id_ecdsa.pub 102 | - id_ed25519.pub 103 | 104 | Sidekick will also get all keys from the `ssh-agent` and try them as well. If you want to use a custom key and not a default one, you would need to add the to your agent first by running `ssh-add KEY_FILE` 105 | 106 |
107 | 108 | Read more details about flags and other options for this command [on the docs](https://www.sidekickdeploy.com/docs/command/init/) 109 | 110 | ### Launch a new application 111 | 112 |
113 | 114 |
115 | 116 | In your application folder, make sure you have a working `Dockerfile` that you can build and run. Also make sure you know at which port your app is expecting to receive traffic. 117 | 118 | Then run: 119 | 120 | ```bash 121 | sidekick launch 122 | ``` 123 | 124 | Then you need to enter the following: 125 | 126 | - Url friendly name of your app - if you opt to use `sslip.io` domain for testing this would be your subdomain 127 | - HTTP exposed port for your app to get requests - Sidekick will scan your docker file to try to extract this number and default it. 128 | - Domain at which you want this application to be reachable - If you choose your own domain make sure to point the domain to your VPS IP address; otherwise we default to `sslip.io` domain so you can play around. 129 | - If you have any `env` file with secrets in it. Sidekick will attempt to find `.env` file in the root of your folder. Sidekick will use `sops` to encrypt your env file and inject the values securely at run time. 130 | 131 | Should take around 2 more mins to be able to visit your application live on the web if all goes well. 132 | 133 |
134 | What does Sidekick do when I run this command 135 | 136 | * Build your docker image locally for linux 137 | * Move the docker image to your VPS directly 138 | * Encrypt your env file, if available and push it to your VPS 139 | * Use sops to decrypt your env file and start and env with the values injected 140 | * Spin up your docker image using docker compose and route traffic to it using Traefik on the specified port 141 |
142 | 143 | ### Deploy a new version 144 | 145 |
146 | 147 |
148 | With your application deployed, it's super simple to deploy a new version. 149 | 150 | At any point any time you need to only run: 151 | 152 | ```bash 153 | sidekick deploy 154 | ``` 155 | 156 | That's all. It won't take long, we use cache from earlier docker images, your latest version should be up soon. 157 | Sidekick will deploy the new version without any downtime - you can see more in the source code. 158 | This command will also do a couple of things behind the scenes. You can check that below 159 | 160 |
161 | What does Sidekick do when I run this command 162 | 163 | * Build your docker image locally for linux 164 | * Compare your latest env file checksum for changes from last time you deployed your application. 165 | * If your env file has changed, sidekick will re-encrypt it and replace the encrypted.env file on your server. 166 | * Deploy the new version with zero downtime deploys so you don't miss any traffic. 167 |
168 | 169 | ### Deploy a preview environment/app 170 | 171 |
172 | 173 |
174 | Sidekick also allows you to deploy preview apps at any point from your application. Preview apps are attached to your commit hash and require a clean git tree before you can initiate them. 175 | Once you have a clean git tree, you can run the following command to deploy a preview app: 176 | 177 | ```bash 178 | sidekick deploy preview 179 | ``` 180 | 181 |
182 | What does Sidekick do when I run this command 183 | 184 | * Build your docker image locally for linux 185 | * Tag the new image with the short checksum of your git commit 186 | * Encrypt your env file, if available and push it to your VPS 187 | * Add a new folder inside your app folder called "preview" where Sidekick will store and manage all your preview deployments 188 | * Deploy a new version of your app reachable on a short hash based subdomain 189 |
190 | 191 | ## Inspiration 192 | 193 | - https://fly.io/ 194 | - https://kamal-deploy.org/ 195 | 196 | ## Vision 197 | 198 | Simple CLI tool that can help you: 199 | 200 | - Setup your VPS 201 | - Deploy all your side projects on a single VPS 202 | - Load balance multiple container per project 203 | - Deploy new versions with Zero downtime 204 | - Deploy preview environments with ease 205 | - Manage env secrets in a secure way 206 | - Connect any number of domains and subdomains to your projects with ease 207 | 208 | ## Remove sidekick 209 | 210 | You can easily remove sidekick if you hate it. 211 | 212 | ```bash 213 | brew uninstall sidekick 214 | ``` 215 | 216 | --- 217 | 218 | ## Roadmap 219 | 220 | I still have a couple more feature I want to add here. Also considering some of those to be on a paid version. 221 | 222 | - ✅ Preview env deployments 223 | - A way to deploy more complicated projects defined in docker compose file 224 | - Better zero downtime deploys with watchtower 225 | - Firewall setup 226 | - Managing multiple VPSs 227 | - Easy way to deploy databases with one command 228 | - TUI for monitoring your VPS 229 | - Streaming down compose logs - ala `fly logs` 230 | - Auto deploy on image push - to work with CICD better 231 | - Git hooks setup for managing migrations and other concerns 232 | -------------------------------------------------------------------------------- /cmd/deploy/deploy.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package deploy 16 | 17 | import ( 18 | "crypto/md5" 19 | "fmt" 20 | "log" 21 | "os" 22 | "os/exec" 23 | "strconv" 24 | "strings" 25 | "time" 26 | 27 | tea "github.com/charmbracelet/bubbletea" 28 | teaLog "github.com/charmbracelet/log" 29 | "github.com/mightymoud/sidekick/render" 30 | "github.com/mightymoud/sidekick/utils" 31 | "github.com/pterm/pterm" 32 | "github.com/spf13/cobra" 33 | "github.com/spf13/viper" 34 | "gopkg.in/yaml.v3" 35 | ) 36 | 37 | var DeployCmd = &cobra.Command{ 38 | Use: "deploy", 39 | Short: "Deploy a new version of your application to your VPS using Sidekick", 40 | Long: `This command deploys a new version of your application to your VPS. 41 | It assumes that your VPS is already configured and that your application is ready for deployment`, 42 | Run: func(cmd *cobra.Command, args []string) { 43 | start := time.Now() 44 | 45 | if configErr := utils.ViperInit(); configErr != nil { 46 | pterm.Error.Println("Sidekick config not found - Run sidekick init") 47 | os.Exit(1) 48 | } 49 | if !utils.FileExists("./sidekick.yml") { 50 | pterm.Error.Println(`Sidekick config not found in current directory Run sidekick launch`) 51 | os.Exit(1) 52 | } 53 | if viper.GetString("secretKey") == "" { 54 | render.GetLogger(teaLog.Options{Prefix: "Backward Compat"}).Error("Recent changes to how Sidekick handles secrets prevents you from launcing a new application.") 55 | render.GetLogger(teaLog.Options{Prefix: "Backward Compat"}).Info("To fix this, run `Sidekick init` with the same server address you have now.") 56 | render.GetLogger(teaLog.Options{Prefix: "Backward Compat"}).Info("Learn more at www.sidekickdeploy.com/docs/design/encryption") 57 | os.Exit(1) 58 | } 59 | 60 | cmdStages := []render.Stage{ 61 | render.MakeStage("Validating connection with VPS", "VPS is reachable", false), 62 | render.MakeStage("Updating secrets if needed", "Env file check complete", false), 63 | render.MakeStage("Building latest docker image of your app", "Latest docker image built", true), 64 | render.MakeStage("Saving docker image locally", "Image saved successfully", false), 65 | render.MakeStage("Moving image to your server", "Image moved and loaded successfully", false), 66 | render.MakeStage("Deploying a new version of your application", "Deployed new version successfully", false), 67 | } 68 | p := tea.NewProgram(render.TuiModel{ 69 | Stages: cmdStages, 70 | BannerMsg: "Deploying a new env of your app 😎", 71 | ActiveIndex: 0, 72 | Quitting: false, 73 | AllDone: false, 74 | }) 75 | 76 | appConfig, loadError := utils.LoadAppConfig() 77 | if loadError != nil { 78 | panic(loadError) 79 | } 80 | replacer := strings.NewReplacer( 81 | "$service_name", appConfig.Name, 82 | "$app_port", fmt.Sprint(appConfig.Port), 83 | "$age_secret_key", viper.GetString("secretKey"), 84 | ) 85 | 86 | go func() { 87 | sshClient, err := utils.Login(viper.GetString("serverAddress"), "sidekick") 88 | if err != nil { 89 | p.Send(render.ErrorMsg{}) 90 | } 91 | p.Send(render.NextStageMsg{}) 92 | 93 | envFileChanged := false 94 | currentEnvFileHash := "" 95 | if appConfig.Env.File != "" { 96 | envFileContent, envFileErr := os.ReadFile(fmt.Sprintf("./%s", appConfig.Env.File)) 97 | if envFileErr != nil { 98 | p.Send(render.ErrorMsg{ErrorStr: envFileErr.Error()}) 99 | } 100 | currentEnvFileHash = fmt.Sprintf("%x", md5.Sum(envFileContent)) 101 | envFileChanged = appConfig.Env.Hash != currentEnvFileHash 102 | if envFileChanged { 103 | // encrypt new env file 104 | envCmd := exec.Command("sh", "-s", "-", viper.GetString("publicKey"), fmt.Sprintf("./%s", appConfig.Env.File)) 105 | envCmd.Stdin = strings.NewReader(utils.EnvEncryptionScript) 106 | envCmdErrPipe, _ := envCmd.StderrPipe() 107 | go render.SendLogsToTUI(envCmdErrPipe, p) 108 | if envCmdErr := envCmd.Run(); envCmdErr != nil { 109 | p.Send(render.ErrorMsg{ErrorStr: envCmdErr.Error()}) 110 | } 111 | encryptSyncCmd := exec.Command("rsync", "-v", "encrypted.env", fmt.Sprintf("%s@%s:%s", "sidekick", viper.Get("serverAddress").(string), fmt.Sprintf("./%s", appConfig.Name))) 112 | encryptSyncCmdErrPipe, _ := encryptSyncCmd.StderrPipe() 113 | go render.SendLogsToTUI(encryptSyncCmdErrPipe, p) 114 | if encryptSyncCmdErr := encryptSyncCmd.Run(); encryptSyncCmdErr != nil { 115 | p.Send(render.ErrorMsg{ErrorStr: encryptSyncCmdErr.Error()}) 116 | time.Sleep(time.Millisecond * 200) 117 | } 118 | } 119 | } 120 | defer os.Remove("encrypted.env") 121 | 122 | p.Send(render.NextStageMsg{}) 123 | 124 | cwd, _ := os.Getwd() 125 | imgFileName := fmt.Sprintf("%s-latest.tar", appConfig.Name) 126 | dockerBuildCmd := exec.Command("docker", "build", "--tag", appConfig.Name, "--progress=plain", "--platform=linux/amd64", cwd) 127 | dockerBuildCmdErrPipe, _ := dockerBuildCmd.StderrPipe() 128 | go render.SendLogsToTUI(dockerBuildCmdErrPipe, p) 129 | 130 | if dockerBuildErr := dockerBuildCmd.Run(); dockerBuildErr != nil { 131 | p.Send(render.ErrorMsg{}) 132 | } 133 | 134 | time.Sleep(time.Millisecond * 100) 135 | 136 | p.Send(render.NextStageMsg{}) 137 | 138 | imgSaveCmd := exec.Command("docker", "save", "-o", imgFileName, appConfig.Name) 139 | imgSaveCmdErrPipe, _ := imgSaveCmd.StderrPipe() 140 | go render.SendLogsToTUI(imgSaveCmdErrPipe, p) 141 | 142 | if imgSaveCmdErr := imgSaveCmd.Run(); imgSaveCmdErr != nil { 143 | p.Send(render.ErrorMsg{}) 144 | } 145 | 146 | time.Sleep(time.Millisecond * 200) 147 | 148 | p.Send(render.NextStageMsg{}) 149 | 150 | remoteDist := fmt.Sprintf("%s@%s:./%s", "sidekick", viper.GetString("serverAddress"), appConfig.Name) 151 | imgMoveCmd := exec.Command("scp", "-C", imgFileName, remoteDist) 152 | imgMoveCmdErrorPipe, _ := imgMoveCmd.StderrPipe() 153 | go render.SendLogsToTUI(imgMoveCmdErrorPipe, p) 154 | 155 | if imgMovCmdErr := imgMoveCmd.Run(); imgMovCmdErr != nil { 156 | p.Send(render.ErrorMsg{}) 157 | } 158 | defer os.Remove(imgFileName) 159 | 160 | time.Sleep(time.Millisecond * 200) 161 | p.Send(render.NextStageMsg{}) 162 | 163 | dockerLoadOutChan, _, sessionErr := utils.RunCommand(sshClient, fmt.Sprintf("cd %s && docker load -i %s-latest.tar", appConfig.Name, appConfig.Name)) 164 | if sessionErr != nil { 165 | log.Fatal("Issue happened loading docker image") 166 | } 167 | 168 | go func() { 169 | p.Send(render.LogMsg{LogLine: <-dockerLoadOutChan + "\n"}) 170 | time.Sleep(time.Millisecond * 100) 171 | }() 172 | 173 | if appConfig.Env.File != "" { 174 | deployScript := replacer.Replace(utils.DeployAppWithEnvScript) 175 | _, runVersionOutChan, sessionErr := utils.RunCommand(sshClient, deployScript) 176 | if sessionErr != nil { 177 | panic(sessionErr) 178 | } 179 | go func() { 180 | p.Send(render.LogMsg{LogLine: <-runVersionOutChan + "\n"}) 181 | time.Sleep(time.Millisecond * 100) 182 | }() 183 | } else { 184 | deployScript := replacer.Replace(utils.DeployAppScript) 185 | _, runOutChan, sessionErr := utils.RunCommand(sshClient, deployScript) 186 | if sessionErr != nil { 187 | panic(sessionErr) 188 | } 189 | go func() { 190 | p.Send(render.LogMsg{LogLine: <-runOutChan + "\n"}) 191 | }() 192 | time.Sleep(time.Second * 2) 193 | } 194 | 195 | cleanOutChan, _, sessionErr := utils.RunCommand(sshClient, fmt.Sprintf("cd %s && rm %s", appConfig.Name, fmt.Sprintf("%s-latest.tar", appConfig.Name))) 196 | if sessionErr != nil { 197 | log.Fatal("Issue happened cleaning up the image file") 198 | } 199 | go func() { 200 | p.Send(render.LogMsg{LogLine: <-cleanOutChan + "\n"}) 201 | time.Sleep(time.Millisecond * 100) 202 | }() 203 | 204 | latestVersion := strings.Split(appConfig.Version, "")[1] 205 | latestVersionInt, _ := strconv.ParseInt(latestVersion, 0, 64) 206 | appConfig.Version = fmt.Sprintf("V%d", latestVersionInt+1) 207 | // env file changed ? -> update hash 208 | if envFileChanged { 209 | appConfig.Env.Hash = currentEnvFileHash 210 | } 211 | ymlData, _ := yaml.Marshal(&appConfig) 212 | os.WriteFile("./sidekick.yml", ymlData, 0644) 213 | 214 | time.Sleep(time.Millisecond * 500) 215 | p.Send(render.AllDoneMsg{Duration: time.Since(start).Round(time.Second), URL: appConfig.Url}) 216 | }() 217 | 218 | if _, err := p.Run(); err != nil { 219 | fmt.Println("Error running program:", err) 220 | os.Exit(1) 221 | } 222 | }, 223 | } 224 | -------------------------------------------------------------------------------- /cmd/destroy.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package cmd 16 | 17 | import ( 18 | "fmt" 19 | 20 | "github.com/spf13/cobra" 21 | ) 22 | 23 | // destroyCmd represents the destroy command 24 | var destroyCmd = &cobra.Command{ 25 | Use: "destroy", 26 | Short: "A command to destroy your app on the VPS and remove the container and the images", 27 | Long: `This command is destructive and will remove everything related to your application from the VPS. Please use it with care`, 28 | Run: func(cmd *cobra.Command, args []string) { 29 | fmt.Println("destroy called") 30 | }, 31 | } 32 | 33 | func init() { 34 | rootCmd.AddCommand(destroyCmd) 35 | 36 | // Here you will define your flags and configuration settings. 37 | 38 | // Cobra supports Persistent Flags which will work for this command 39 | // and all subcommands, e.g.: 40 | // destroyCmd.PersistentFlags().String("foo", "", "A help for foo") 41 | 42 | // Cobra supports local flags which will only run when this command 43 | // is called directly, e.g.: 44 | // destroyCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") 45 | } 46 | -------------------------------------------------------------------------------- /cmd/init.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package cmd 16 | 17 | import ( 18 | "errors" 19 | "fmt" 20 | "log" 21 | "os" 22 | "os/exec" 23 | "strings" 24 | 25 | "github.com/mightymoud/sidekick/render" 26 | "github.com/mightymoud/sidekick/utils" 27 | "github.com/pterm/pterm" 28 | "github.com/spf13/cobra" 29 | "github.com/spf13/viper" 30 | "golang.org/x/crypto/ssh" 31 | ) 32 | 33 | var InitCmd = &cobra.Command{ 34 | Use: "init", 35 | Short: "Init sidekick CLI and configure your VPS to host your apps", 36 | Long: `This command will run you through the setup steps to get sidekick loaded on your VPS. 37 | You wil need to provide your VPS IPv4 address and a registry to host your docker images. 38 | `, 39 | Run: func(cmd *cobra.Command, args []string) { 40 | pterm.DefaultBasicText.Println("Welcome to Sidekick. We need to collect some details from you first") 41 | 42 | render.RenderSidekickBig() 43 | 44 | if configErr := utils.ViperInit(); configErr != nil { 45 | if errors.As(configErr, &viper.ConfigFileNotFoundError{}) { 46 | initConfig() 47 | } else { 48 | pterm.Error.Printfln("%s", configErr) 49 | os.Exit(1) 50 | } 51 | } 52 | 53 | skipPromptsFlag, skipFlagErr := cmd.Flags().GetBool("yes") 54 | if skipFlagErr != nil { 55 | fmt.Println(skipFlagErr) 56 | } 57 | 58 | server, serverFlagErr := cmd.Flags().GetString("server") 59 | if serverFlagErr != nil { 60 | fmt.Println(serverFlagErr) 61 | } 62 | certEmail, emailFlagError := cmd.Flags().GetString("email") 63 | if emailFlagError != nil { 64 | fmt.Println(emailFlagError) 65 | } 66 | 67 | if server == "" { 68 | serverTextInput := pterm.DefaultInteractiveTextInput 69 | serverTextInput.DefaultText = "Please enter the IPv4 Address of your VPS" 70 | server, _ = serverTextInput.Show() 71 | if !utils.IsValidIPAddress(server) { 72 | pterm.Error.Printfln("You entered an incorrect IP Address - %s", server) 73 | os.Exit(0) 74 | } 75 | } 76 | 77 | if certEmail == "" { 78 | certEmailTextInput := pterm.DefaultInteractiveTextInput 79 | certEmailTextInput.DefaultText = "Please enter an email for use with TLS certs" 80 | certEmail, _ = certEmailTextInput.Show() 81 | if certEmail == "" { 82 | pterm.Error.Println("An email is needed before you proceed") 83 | os.Exit(0) 84 | } 85 | } 86 | 87 | // if keys exist -> a server is already setup 88 | publicKey := viper.GetString("publicKey") 89 | secretKey := viper.GetString("secretKey") 90 | if publicKey != "" && server != viper.GetString("serverAddress") && !skipPromptsFlag { 91 | prompt := pterm.DefaultInteractiveConfirm 92 | prompt.DefaultText = "A server was previously setup with Sidekick. Would you like to override the settings?" 93 | result, showErr := prompt.Show() 94 | if showErr != nil { 95 | pterm.Error.Printfln("Something went wrong: %s", showErr) 96 | os.Exit(1) 97 | } 98 | if !result { 99 | pterm.Println() 100 | pterm.Error.Println("Currently Sidekick only supports one server per setup") 101 | pterm.Println() 102 | os.Exit(0) 103 | } 104 | } 105 | 106 | viper.Set("serverAddress", server) 107 | viper.Set("certEmail", certEmail) 108 | 109 | pterm.Println() 110 | pterm.DefaultHeader.WithFullWidth().Println("Sidekick booting up! 🚀") 111 | pterm.Println() 112 | 113 | var sshClient *ssh.Client 114 | var initSessionErr error 115 | var loggedInUser string 116 | users := []string{"root", "sidekick"} 117 | canConnect := false 118 | for _, user := range users { 119 | sshClient, initSessionErr = utils.Login(server, user) 120 | if initSessionErr != nil { 121 | continue 122 | } 123 | loggedInUser = user 124 | canConnect = true 125 | break 126 | } 127 | if !canConnect { 128 | pterm.Error.Println("Unable to establish SSH connection to the server") 129 | os.Exit(1) 130 | } 131 | 132 | multi := pterm.DefaultMultiPrinter 133 | localReqsChecks, _ := utils.GetSpinner().WithWriter(multi.NewWriter()).Start("Setting up your local env") 134 | rootLoginSpinner, _ := utils.GetSpinner().WithWriter(multi.NewWriter()).Start("Logging in with root") 135 | stage0Spinner, _ := utils.GetSpinner().WithWriter(multi.NewWriter()).Start("Adding user Sidekick") 136 | sidekickLoginSpinner, _ := utils.GetSpinner().WithWriter(multi.NewWriter()).Start("Logging into with sidekick user") 137 | stage1Spinner, _ := utils.GetSpinner().WithWriter(multi.NewWriter()).Start("Setting up VPS") 138 | stage2Spinner, _ := utils.GetSpinner().WithWriter(multi.NewWriter()).Start("Setting up Docker") 139 | stage3Spinner, _ := utils.GetSpinner().WithWriter(multi.NewWriter()).Start("Setting up Traefik") 140 | pterm.Println() 141 | multi.Start() 142 | 143 | localReqsChecks.Sequence = []string{"▀ ", " ▀", " ▄", "▄ "} 144 | 145 | _, sopsErr := exec.LookPath("sops") 146 | if sopsErr != nil { 147 | _, err := exec.LookPath("brew") 148 | if err != nil { 149 | log.Fatalf("Failed to run brew. Brew is required to use Sidekick: %s", err) 150 | } 151 | installSopsCmd := exec.Command("brew", "install", "sops") 152 | _, installSopsCmdErr := installSopsCmd.CombinedOutput() 153 | if installSopsCmdErr != nil { 154 | log.Fatalf("Failed to install Sops. Sops is needed to encrypt your local env: %s", installSopsCmdErr) 155 | } 156 | } 157 | _, ageErr := exec.LookPath("age") 158 | if ageErr != nil { 159 | // log.Println("Age not found, installing Age") 160 | _, err := exec.LookPath("brew") 161 | if err != nil { 162 | log.Fatalf("Failed to run brew. Brew is required to use Sidekick: %s", err) 163 | } 164 | installAgeCmd := exec.Command("brew", "install", "age") 165 | _, installAgeCmdErr := installAgeCmd.CombinedOutput() 166 | if installAgeCmdErr != nil { 167 | log.Fatalf("Failed to install Age. Age is needed to encrypt your local env: %s", installAgeCmd) 168 | } 169 | } 170 | 171 | localReqsChecks.Success("Installed local requirements successfully") 172 | 173 | rootLoginSpinner.Success("Logged in successfully!") 174 | 175 | stage0Spinner.Sequence = []string{"▀ ", " ▀", " ▄", "▄ "} 176 | 177 | hasSidekickUser := true 178 | outChan, _, sessionErr := utils.RunCommand(sshClient, "id -u sidekick") 179 | if sessionErr != nil { 180 | hasSidekickUser = false 181 | } else { 182 | select { 183 | case output := <-outChan: 184 | if output != "0" { 185 | hasSidekickUser = true 186 | } 187 | } 188 | } 189 | if !hasSidekickUser && loggedInUser == "root" { 190 | if err := utils.RunStage(sshClient, utils.UsersetupStage); err != nil { 191 | stage0Spinner.Fail(utils.UsersetupStage.SpinnerFailMessage) 192 | panic(err) 193 | } 194 | 195 | } 196 | stage0Spinner.Success(utils.UsersetupStage.SpinnerSuccessMessage) 197 | 198 | sidekickLoginSpinner.Sequence = []string{"▀ ", " ▀", " ▄", "▄ "} 199 | sidekickSshClient, err := utils.Login(server, "sidekick") 200 | if err != nil { 201 | sidekickLoginSpinner.Fail("Something went wrong logging in to your VPS") 202 | log.Fatal(err) 203 | } 204 | sidekickLoginSpinner.Success("Logged in successfully with new user!") 205 | 206 | stage1Spinner.Sequence = []string{"▀ ", " ▀", " ▄", "▄ "} 207 | if err := utils.RunStage(sidekickSshClient, utils.SetupStage); err != nil { 208 | stage1Spinner.Fail(utils.SetupStage.SpinnerFailMessage) 209 | panic(err) 210 | } 211 | 212 | if publicKey == "" || secretKey == "" { 213 | ageKeygenCmd := exec.Command("age-keygen") 214 | cmdOutput, ageKeygenCmdErr := ageKeygenCmd.Output() 215 | if ageKeygenCmdErr != nil { 216 | log.Fatalf("Failed to run brew. Brew is required to use Sidekick: %s", ageKeygenCmd) 217 | os.Exit(1) 218 | } 219 | ageKeyOut := string(cmdOutput) 220 | outputSlice := strings.Split(ageKeyOut, "\n") 221 | 222 | secretKey = outputSlice[2] 223 | publicKey = strings.ReplaceAll(strings.Split(outputSlice[1], ":")[1], " ", "") 224 | } 225 | viper.Set("publicKey", publicKey) 226 | viper.Set("secretKey", secretKey) 227 | 228 | stage1Spinner.Success(utils.SetupStage.SpinnerSuccessMessage) 229 | 230 | stage2Spinner.Sequence = []string{"▀ ", " ▀", " ▄", "▄ "} 231 | dockerReady := false 232 | dockOutCh, _, sessionErr := utils.RunCommand(sshClient, `command -v docker &> /dev/null && command -v docker compose &> /dev/null && echo "1" || echo "0"`) 233 | if sessionErr != nil { 234 | log.Fatal("Issue checking Docker") 235 | } 236 | 237 | select { 238 | case output := <-dockOutCh: 239 | if output == "1" { 240 | dockerReady = true 241 | } 242 | break 243 | } 244 | if !dockerReady { 245 | if err := utils.RunStage(sidekickSshClient, utils.DockerStage); err != nil { 246 | stage2Spinner.Fail(utils.DockerStage.SpinnerFailMessage) 247 | panic(err) 248 | } 249 | } 250 | stage2Spinner.Success(utils.DockerStage.SpinnerSuccessMessage) 251 | 252 | stage3Spinner.Sequence = []string{"▀ ", " ▀", " ▄", "▄ "} 253 | traefikSetup := false 254 | trOutCh, _, sessionErr := utils.RunCommand(sshClient, `[ -d "sidekick-traefik" ] && echo "1" || echo "0"`) 255 | if sessionErr != nil { 256 | log.Fatal("Issue with checking folder traefik") 257 | } 258 | 259 | select { 260 | case output := <-trOutCh: 261 | if output == "1" { 262 | traefikSetup = true 263 | } 264 | break 265 | } 266 | traefikStage := utils.GetTraefikStage(certEmail) 267 | if !traefikSetup { 268 | if err := utils.RunStage(sidekickSshClient, traefikStage); err != nil { 269 | stage3Spinner.Fail(traefikStage.SpinnerFailMessage) 270 | panic(err) 271 | } 272 | } 273 | stage3Spinner.Success(traefikStage.SpinnerSuccessMessage) 274 | 275 | if err := viper.WriteConfig(); err != nil { 276 | panic(err) 277 | } 278 | multi.Stop() 279 | 280 | pterm.Println() 281 | pterm.Info.Println("Your VPS is ready! You can now run Sidekick launch in your app folder") 282 | pterm.Println() 283 | }, 284 | } 285 | 286 | func initConfig() { 287 | home, err := os.UserHomeDir() 288 | cobra.CheckErr(err) 289 | 290 | configPath := fmt.Sprintf("%s/.config/sidekick", home) 291 | configFile := fmt.Sprintf("%s/default.yaml", configPath) 292 | 293 | makeDirErr := os.MkdirAll(configPath, os.ModePerm) 294 | if makeDirErr != nil { 295 | log.Fatalf("Error creating directory: %v\n", makeDirErr) 296 | os.Exit(1) 297 | } 298 | 299 | viper.AddConfigPath(configPath) 300 | viper.SetConfigType("yaml") 301 | viper.SetConfigName("default") 302 | file, fileCreateErr := os.Create(configFile) 303 | if fileCreateErr != nil { 304 | log.Fatalf("Error creating configFile: %v\n", fileCreateErr) 305 | os.Exit(1) 306 | } 307 | 308 | file.Close() 309 | } 310 | 311 | func init() { 312 | rootCmd.AddCommand(InitCmd) 313 | 314 | InitCmd.Flags().StringP("server", "s", "", "Set the IP address of your Server") 315 | InitCmd.Flags().StringP("email", "e", "", "An email address to be used for SSL certs") 316 | InitCmd.Flags().BoolP("yes", "y", false, "Skip all validation prompts") 317 | } 318 | -------------------------------------------------------------------------------- /cmd/launch/launch.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package launch 16 | 17 | import ( 18 | "fmt" 19 | "os" 20 | "os/exec" 21 | "strconv" 22 | "strings" 23 | "time" 24 | 25 | tea "github.com/charmbracelet/bubbletea" 26 | "github.com/charmbracelet/log" 27 | "github.com/mightymoud/sidekick/render" 28 | "github.com/mightymoud/sidekick/utils" 29 | "github.com/spf13/cobra" 30 | "github.com/spf13/viper" 31 | "gopkg.in/yaml.v3" 32 | ) 33 | 34 | var LaunchCmd = &cobra.Command{ 35 | Use: "launch", 36 | Short: "Launch a new application to host on your VPS with Sidekick", 37 | Long: `This command will run you through the basic setup to add a new application to your VPS.`, 38 | Run: func(cmd *cobra.Command, args []string) { 39 | start := time.Now() 40 | 41 | if configErr := utils.ViperInit(); configErr != nil { 42 | render.GetLogger(log.Options{Prefix: "Sidekick Config"}).Fatalf("%s", configErr) 43 | } 44 | 45 | if viper.GetString("secretKey") == "" { 46 | render.GetLogger(log.Options{Prefix: "Backward Compat"}).Error("Recent changes to how Sidekick handles secrets prevents you from launcing a new application.") 47 | render.GetLogger(log.Options{Prefix: "Backward Compat"}).Info("To fix this, run `Sidekick init` with the same server address you have now.") 48 | render.GetLogger(log.Options{Prefix: "Backward Compat"}).Info("Learn more at www.sidekickdeploy.com/docs/design/encryption") 49 | os.Exit(1) 50 | } 51 | 52 | if utils.FileExists("./sidekick.yml") { 53 | render.GetLogger(log.Options{Prefix: "Sidekick Setup"}).Error("Sidekick config exits in this project.") 54 | render.GetLogger(log.Options{Prefix: "Sidekick Setup"}).Info("You can deploy a new version of your application with Sidekick deploy.") 55 | os.Exit(1) 56 | } 57 | 58 | if utils.FileExists("./Dockerfile") { 59 | render.GetLogger(log.Options{Prefix: "Dockerfile"}).Info("Detected - scanning file for details") 60 | } else { 61 | render.GetLogger(log.Options{Prefix: "Dockerfile"}).Fatal("No dockerfile found in current directory.") 62 | } 63 | 64 | res, err := os.ReadFile("./Dockerfile") 65 | if err != nil { 66 | render.GetLogger(log.Options{Prefix: "Dockerfile"}).Fatal("Unable to process your dockerfile") 67 | } 68 | 69 | appPort := "" 70 | for _, line := range strings.Split(string(res), "\n") { 71 | if strings.HasPrefix(line, "EXPOSE ") { 72 | appPort = strings.TrimPrefix(line, "EXPOSE ") 73 | } 74 | } 75 | 76 | appName := render.GenerateTextQuestion("Please enter your app url friendly app name", "", "will identify your app containers") 77 | appPort = render.GenerateTextQuestion("Please enter the port at which the app receives request", appPort, "") 78 | appDomain := render.GenerateTextQuestion("Please enter the domain to point the app to", fmt.Sprintf("%s.%s.sslip.io", appName, viper.Get("serverAddress").(string)), "must point to your VPS address") 79 | envFileName := render.GenerateTextQuestion("Please enter which env file you would like to load", ".env", "") 80 | 81 | hasEnvFile := false 82 | dockerEnvProperty := []string{} 83 | envFileChecksum := "" 84 | if utils.FileExists(fmt.Sprintf("./%s", envFileName)) { 85 | hasEnvFile = true 86 | render.GetLogger(log.Options{Prefix: "Env File"}).Infof("Detected - Loading env vars from %s", envFileName) 87 | envHandleErr := utils.HandleEnvFile(envFileName, &dockerEnvProperty, &envFileChecksum) 88 | if envHandleErr != nil { 89 | render.GetLogger(log.Options{Prefix: "Env File"}).Fatalf("Something went wrong %s", envHandleErr) 90 | } 91 | defer os.Remove("encrypted.env") 92 | } else { 93 | render.GetLogger(log.Options{Prefix: "Env File"}).Info("Not Detected - Skipping env parsing") 94 | } 95 | 96 | // make a docker service 97 | imageName := appName 98 | newService := utils.DockerService{ 99 | Image: imageName, 100 | Restart: "unless-stopped", 101 | Labels: []string{ 102 | "traefik.enable=true", 103 | fmt.Sprintf("traefik.http.routers.%s.rule=Host(`%s`)", appName, appDomain), 104 | fmt.Sprintf("traefik.http.services.%s.loadbalancer.server.port=%s", appName, appPort), 105 | fmt.Sprintf("traefik.http.routers.%s.tls=true", appName), 106 | fmt.Sprintf("traefik.http.routers.%s.tls.certresolver=default", appName), 107 | "traefik.docker.network=sidekick", 108 | }, 109 | Environment: dockerEnvProperty, 110 | Networks: []string{ 111 | "sidekick", 112 | }, 113 | } 114 | newDockerCompose := utils.DockerComposeFile{ 115 | Services: map[string]utils.DockerService{ 116 | appName: newService, 117 | }, 118 | Networks: map[string]utils.DockerNetwork{ 119 | "sidekick": { 120 | External: true, 121 | }, 122 | }, 123 | } 124 | dockerComposeFile, err := yaml.Marshal(&newDockerCompose) 125 | if err != nil { 126 | fmt.Printf("Error marshalling YAML: %v\n", err) 127 | return 128 | } 129 | err = os.WriteFile("docker-compose.yaml", dockerComposeFile, 0644) 130 | if err != nil { 131 | fmt.Printf("Error writing file: %v\n", err) 132 | return 133 | } 134 | defer os.Remove("docker-compose.yaml") 135 | 136 | cmdStages := []render.Stage{ 137 | render.MakeStage("Validating connection with VPS", "VPS is reachable", false), 138 | render.MakeStage("Building latest docker image of your app", "Latest docker image built", true), 139 | render.MakeStage("Saving docker image locally", "Image saved successfully", false), 140 | render.MakeStage("Moving image to your server", "Image moved and loaded successfully", false), 141 | render.MakeStage("Setting up your application", "Application setup successfully", false), 142 | } 143 | p := tea.NewProgram(render.TuiModel{ 144 | Stages: cmdStages, 145 | BannerMsg: "Launching your application on your VPS 🚀", 146 | ActiveIndex: 0, 147 | Quitting: false, 148 | AllDone: false, 149 | }) 150 | 151 | go func() { 152 | sshClient, err := utils.Login(viper.GetString("serverAddress"), "sidekick") 153 | if err != nil { 154 | p.Send(render.ErrorMsg{ErrorStr: "Something went wrong logging in to your VPS"}) 155 | } 156 | p.Send(render.NextStageMsg{}) 157 | 158 | cwd, _ := os.Getwd() 159 | dockerBuildCmd := exec.Command("docker", "build", "--tag", appName, "--progress=plain", "--platform=linux/amd64", cwd) 160 | dockerBuildCmdErrPipe, _ := dockerBuildCmd.StderrPipe() 161 | go render.SendLogsToTUI(dockerBuildCmdErrPipe, p) 162 | 163 | if dockerBuildErr := dockerBuildCmd.Run(); dockerBuildErr != nil { 164 | p.Send(render.ErrorMsg{}) 165 | } 166 | 167 | time.Sleep(time.Millisecond * 100) 168 | 169 | p.Send(render.NextStageMsg{}) 170 | 171 | imgFileName := fmt.Sprintf("%s-latest.tar", appName) 172 | imgSaveCmd := exec.Command("docker", "save", "-o", imgFileName, appName) 173 | imgSaveCmdErrPipe, _ := imgSaveCmd.StderrPipe() 174 | go render.SendLogsToTUI(imgSaveCmdErrPipe, p) 175 | 176 | if imgSaveCmdErr := imgSaveCmd.Run(); imgSaveCmdErr != nil { 177 | p.Send(render.ErrorMsg{}) 178 | } 179 | 180 | time.Sleep(time.Millisecond * 100) 181 | 182 | p.Send(render.NextStageMsg{}) 183 | 184 | _, _, sessionErr := utils.RunCommand(sshClient, fmt.Sprintf("mkdir %s", appName)) 185 | if sessionErr != nil { 186 | p.Send(render.ErrorMsg{ErrorStr: sessionErr.Error()}) 187 | } 188 | 189 | remoteDist := fmt.Sprintf("%s@%s:./%s", "sidekick", viper.GetString("serverAddress"), appName) 190 | imgMoveCmd := exec.Command("scp", "-C", imgFileName, remoteDist) 191 | imgMoveCmdErrorPipe, _ := imgMoveCmd.StderrPipe() 192 | go render.SendLogsToTUI(imgMoveCmdErrorPipe, p) 193 | 194 | if imgMovCmdErr := imgMoveCmd.Run(); imgMovCmdErr != nil { 195 | p.Send(render.ErrorMsg{}) 196 | } 197 | defer os.Remove(imgFileName) 198 | 199 | time.Sleep(time.Millisecond * 200) 200 | 201 | dockerLoadOutChan, _, sessionErr := utils.RunCommand(sshClient, fmt.Sprintf("cd %s && docker load -i %s && rm %s", appName, imgFileName, imgFileName)) 202 | go func() { 203 | p.Send(render.LogMsg{LogLine: <-dockerLoadOutChan + "\n"}) 204 | time.Sleep(time.Millisecond * 50) 205 | }() 206 | if sessionErr != nil { 207 | time.Sleep(time.Millisecond * 100) 208 | p.Send(render.ErrorMsg{ErrorStr: sessionErr.Error()}) 209 | } 210 | 211 | time.Sleep(time.Millisecond * 100) 212 | p.Send(render.NextStageMsg{}) 213 | 214 | rsyncCmd := exec.Command("rsync", "docker-compose.yaml", fmt.Sprintf("%s@%s:%s", "sidekick", viper.GetString("serverAddress"), fmt.Sprintf("./%s", appName))) 215 | rsyncCmErr := rsyncCmd.Run() 216 | if rsyncCmErr != nil { 217 | p.Send(render.ErrorMsg{ErrorStr: rsyncCmErr.Error()}) 218 | } 219 | 220 | if hasEnvFile { 221 | encryptSync := exec.Command("rsync", "encrypted.env", fmt.Sprintf("%s@%s:%s", "sidekick", viper.GetString("serverAddress"), fmt.Sprintf("./%s", appName))) 222 | encryptSyncErr := encryptSync.Run() 223 | if encryptSyncErr != nil { 224 | p.Send(render.ErrorMsg{ErrorStr: encryptSyncErr.Error()}) 225 | } 226 | 227 | runAppCmdOutChan, _, sessionErr1 := utils.RunCommand(sshClient, fmt.Sprintf(`cd %s && export SOPS_AGE_KEY=%s && sops exec-env encrypted.env 'docker compose -p sidekick up -d'`, appName, viper.GetString("secretKey"))) 228 | go func() { 229 | p.Send(render.LogMsg{LogLine: <-runAppCmdOutChan + "\n"}) 230 | time.Sleep(time.Millisecond * 50) 231 | }() 232 | if sessionErr1 != nil { 233 | p.Send(render.ErrorMsg{ErrorStr: sessionErr1.Error()}) 234 | } 235 | } else { 236 | runAppCmdOutChan, _, sessionErr1 := utils.RunCommand(sshClient, fmt.Sprintf(`cd %s && docker compose -p sidekick up -d`, appName)) 237 | go func() { 238 | p.Send(render.LogMsg{LogLine: <-runAppCmdOutChan + "\n"}) 239 | time.Sleep(time.Millisecond * 50) 240 | }() 241 | if sessionErr1 != nil { 242 | p.Send(render.ErrorMsg{ErrorStr: sessionErr1.Error()}) 243 | } 244 | } 245 | 246 | portNumber, err := strconv.ParseUint(appPort, 0, 64) 247 | if err != nil { 248 | panic(err) 249 | } 250 | envConfig := utils.SidekickAppEnvConfig{} 251 | if hasEnvFile { 252 | envConfig.File = envFileName 253 | envConfig.Hash = envFileChecksum 254 | } 255 | // save app config in same folder 256 | sidekickAppConfig := utils.SidekickAppConfig{ 257 | Name: appName, 258 | Version: "V1", 259 | Port: portNumber, 260 | Url: appDomain, 261 | CreatedAt: time.Now().Format(time.UnixDate), 262 | Env: envConfig, 263 | } 264 | ymlData, _ := yaml.Marshal(&sidekickAppConfig) 265 | os.WriteFile("./sidekick.yml", ymlData, 0644) 266 | p.Send(render.AllDoneMsg{Duration: time.Since(start).Round(time.Second), URL: appDomain}) 267 | }() 268 | 269 | if _, err := p.Run(); err != nil { 270 | fmt.Println("Error running program:", err) 271 | os.Exit(1) 272 | } 273 | 274 | }, 275 | } 276 | -------------------------------------------------------------------------------- /cmd/preview/list/list.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package previewList 16 | 17 | import ( 18 | "fmt" 19 | "os" 20 | 21 | "github.com/charmbracelet/huh" 22 | "github.com/charmbracelet/lipgloss" 23 | "github.com/charmbracelet/lipgloss/table" 24 | "github.com/charmbracelet/log" 25 | "github.com/mightymoud/sidekick/render" 26 | "github.com/mightymoud/sidekick/utils" 27 | "github.com/spf13/cobra" 28 | ) 29 | 30 | // listCmd represents the list command 31 | var ListCmd = &cobra.Command{ 32 | Use: "list", 33 | Aliases: []string{"ls"}, 34 | Short: "This command lists all the preview environments", 35 | Long: `This command lists all the preview environments that are currently running on your VPS.`, 36 | Run: func(cmd *cobra.Command, args []string) { 37 | appConfig, appConfigErr := utils.LoadAppConfig() 38 | if appConfigErr != nil { 39 | log.Fatalf("Unable to load your config file. Might be corrupted") 40 | } 41 | if len(appConfig.PreviewEnvs) == 0 { 42 | render.GetLogger(log.Options{Prefix: "Preview Envs"}).Info("Not Found in current project") 43 | os.Exit(0) 44 | } 45 | header := lipgloss.NewStyle().Foreground(lipgloss.Color("77")).MarginTop(1).MarginLeft(1).Render("Currently running preview envs:") 46 | tableString := table.New(). 47 | Border(lipgloss.RoundedBorder()). 48 | BorderStyle(lipgloss.NewStyle().Foreground(lipgloss.Color("99"))). 49 | StyleFunc(func(row, col int) lipgloss.Style { 50 | switch { 51 | case row == 0: 52 | return lipgloss.NewStyle().Foreground(lipgloss.Color("60")).Align(lipgloss.Center) 53 | default: 54 | return lipgloss.NewStyle().Foreground(lipgloss.Color("78")).PaddingLeft(1).PaddingRight(1) 55 | } 56 | }). 57 | Headers("Commit", "Image", "Deployed At", "URL") 58 | 59 | hashSlice := []huh.Option[string]{} 60 | for v := range appConfig.PreviewEnvs { 61 | hashSlice = append(hashSlice, huh.NewOption(v, v)) 62 | tableString.Row(v, appConfig.PreviewEnvs[v].Image, appConfig.PreviewEnvs[v].CreatedAt, appConfig.PreviewEnvs[v].Url) 63 | } 64 | fmt.Println(header) 65 | fmt.Println(tableString) 66 | }, 67 | } 68 | -------------------------------------------------------------------------------- /cmd/preview/preview.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package preview 16 | 17 | import ( 18 | "fmt" 19 | "os" 20 | "os/exec" 21 | "strings" 22 | "time" 23 | 24 | tea "github.com/charmbracelet/bubbletea" 25 | "github.com/charmbracelet/log" 26 | previewList "github.com/mightymoud/sidekick/cmd/preview/list" 27 | previewRemove "github.com/mightymoud/sidekick/cmd/preview/remove" 28 | "github.com/mightymoud/sidekick/render" 29 | "github.com/mightymoud/sidekick/utils" 30 | "github.com/spf13/cobra" 31 | "github.com/spf13/viper" 32 | "gopkg.in/yaml.v3" 33 | ) 34 | 35 | var PreviewCmd = &cobra.Command{ 36 | Use: "preview", 37 | Short: "Deploy a preview environment for your application", 38 | Long: `Sidekick allows you to deploy preview environment based on commit hash`, 39 | Run: func(cmd *cobra.Command, args []string) { 40 | start := time.Now() 41 | 42 | if configErr := utils.ViperInit(); configErr != nil { 43 | render.GetLogger(log.Options{Prefix: "Sidekick Config"}).Fatalf("%s", configErr) 44 | } 45 | appConfig, appConfigErr := utils.LoadAppConfig() 46 | if appConfigErr != nil { 47 | render.GetLogger(log.Options{Prefix: "Sidekick Setup"}).Error("Sidekick config exits in this project.") 48 | render.GetLogger(log.Options{Prefix: "Sidekick Setup"}).Info("You can deploy a new version of your application with Sidekick deploy.") 49 | os.Exit(1) 50 | } 51 | 52 | if viper.GetString("secretKey") == "" { 53 | render.GetLogger(log.Options{Prefix: "Backward Compat"}).Error("Recent changes to how Sidekick handles secrets prevents you from launcing a new application.") 54 | render.GetLogger(log.Options{Prefix: "Backward Compat"}).Info("To fix this, run `Sidekick init` with the same server address you have now.") 55 | render.GetLogger(log.Options{Prefix: "Backward Compat"}).Info("Learn more at www.sidekickdeploy.com/docs/design/encryption") 56 | os.Exit(1) 57 | } 58 | 59 | gitTreeCheck := exec.Command("sh", "-s", "-") 60 | gitTreeCheck.Stdin = strings.NewReader(utils.CheckGitTreeScript) 61 | output, _ := gitTreeCheck.Output() 62 | if string(output) != "all good\n" { 63 | render.GetLogger(log.Options{Prefix: "Preview Cmd"}).Error("Please commit any changes to git before deploying a preview environment") 64 | os.Exit(1) 65 | } 66 | 67 | gitShortHashCmd := exec.Command("sh", "-s", "-") 68 | gitShortHashCmd.Stdin = strings.NewReader("git rev-parse --short HEAD") 69 | hashOutput, hashErr := gitShortHashCmd.Output() 70 | if hashErr != nil { 71 | render.GetLogger(log.Options{Prefix: "Preview Cmd"}).Error("Issue occurred getting git commit hash: %s", hashErr) 72 | os.Exit(1) 73 | } 74 | deployHash := strings.TrimSuffix(string(hashOutput), "\n") 75 | 76 | cmdStages := []render.Stage{ 77 | render.MakeStage("Validating connection with VPS", "VPS is reachable", false), 78 | render.MakeStage("Building latest docker image of your app", "Latest docker image built", true), 79 | render.MakeStage("Saving docker image locally", "Image saved successfully", false), 80 | render.MakeStage("Moving image to your server", "Image moved and loaded successfully", false), 81 | render.MakeStage("Deploying a preview env of your application", "Preview env setup successfully", false), 82 | } 83 | p := tea.NewProgram(render.TuiModel{ 84 | Stages: cmdStages, 85 | BannerMsg: "Deploying a preview env of your app 😎", 86 | ActiveIndex: 0, 87 | Quitting: false, 88 | AllDone: false, 89 | }) 90 | 91 | go func() { 92 | sshClient, err := utils.Login(viper.GetString("serverAddress"), "sidekick") 93 | if err != nil { 94 | p.Send(render.ErrorMsg{}) 95 | } 96 | p.Send(render.NextStageMsg{}) 97 | 98 | dockerEnvProperty := []string{} 99 | envFileChecksum := "" 100 | if appConfig.Env.File != "" { 101 | envErr := utils.HandleEnvFile(appConfig.Env.File, &dockerEnvProperty, &envFileChecksum) 102 | if envErr != nil { 103 | panic(envErr) 104 | } 105 | } 106 | 107 | imageName := fmt.Sprintf("%s:%s", appConfig.Name, deployHash) 108 | serviceName := fmt.Sprintf("%s-%s", appConfig.Name, deployHash) 109 | previewURL := fmt.Sprintf("%s.%s", deployHash, appConfig.Url) 110 | newService := utils.DockerService{ 111 | Image: imageName, 112 | Labels: []string{ 113 | "traefik.enable=true", 114 | fmt.Sprintf("traefik.http.routers.%s.rule=Host(`%s`)", serviceName, previewURL), 115 | fmt.Sprintf("traefik.http.services.%s.loadbalancer.server.port=%s", serviceName, fmt.Sprint(appConfig.Port)), 116 | fmt.Sprintf("traefik.http.routers.%s.tls=true", serviceName), 117 | fmt.Sprintf("traefik.http.routers.%s.tls.certresolver=default", serviceName), 118 | "traefik.docker.network=sidekick", 119 | }, 120 | Environment: dockerEnvProperty, 121 | Networks: []string{ 122 | "sidekick", 123 | }, 124 | } 125 | newDockerCompose := utils.DockerComposeFile{ 126 | Services: map[string]utils.DockerService{ 127 | serviceName: newService, 128 | }, 129 | Networks: map[string]utils.DockerNetwork{ 130 | "sidekick": { 131 | External: true, 132 | }, 133 | }, 134 | } 135 | dockerComposeFile, err := yaml.Marshal(&newDockerCompose) 136 | if err != nil { 137 | fmt.Printf("Error marshalling YAML: %v\n", err) 138 | return 139 | } 140 | err = os.WriteFile("docker-compose.yaml", dockerComposeFile, 0644) 141 | if err != nil { 142 | fmt.Printf("Error writing file: %v\n", err) 143 | return 144 | } 145 | 146 | cwd, _ := os.Getwd() 147 | dockerImage := fmt.Sprintf("%s:%s", appConfig.Name, deployHash) 148 | dockerBuildCmd := exec.Command("docker", "build", "--tag", dockerImage, "--progress=plain", "--platform=linux/amd64", cwd) 149 | dockerBuildCmdErrPipe, _ := dockerBuildCmd.StderrPipe() 150 | go render.SendLogsToTUI(dockerBuildCmdErrPipe, p) 151 | 152 | if dockerBuildErr := dockerBuildCmd.Run(); dockerBuildErr != nil { 153 | p.Send(render.ErrorMsg{}) 154 | } 155 | 156 | time.Sleep(time.Millisecond * 100) 157 | 158 | p.Send(render.NextStageMsg{}) 159 | 160 | imgFileName := fmt.Sprintf("%s-%s.tar", appConfig.Name, deployHash) 161 | imgSaveCmd := exec.Command("docker", "save", "-o", imgFileName, dockerImage) 162 | imgSaveCmdErrPipe, _ := imgSaveCmd.StderrPipe() 163 | go render.SendLogsToTUI(imgSaveCmdErrPipe, p) 164 | 165 | if imgSaveCmdErr := imgSaveCmd.Run(); imgSaveCmdErr != nil { 166 | p.Send(render.ErrorMsg{}) 167 | } 168 | 169 | time.Sleep(time.Millisecond * 100) 170 | 171 | p.Send(render.NextStageMsg{}) 172 | 173 | _, _, sessionErr0 := utils.RunCommand(sshClient, fmt.Sprintf(`mkdir -p %s/preview/%s`, appConfig.Name, deployHash)) 174 | if sessionErr0 != nil { 175 | p.Send(render.ErrorMsg{ErrorStr: sessionErr0.Error()}) 176 | } 177 | 178 | remoteDist := fmt.Sprintf("%s@%s:./%s", "sidekick", viper.GetString("serverAddress"), appConfig.Name) 179 | imgMoveCmd := exec.Command("scp", "-C", imgFileName, remoteDist) 180 | imgMoveCmdErrorPipe, _ := imgMoveCmd.StderrPipe() 181 | go render.SendLogsToTUI(imgMoveCmdErrorPipe, p) 182 | 183 | if imgMovCmdErr := imgMoveCmd.Run(); imgMovCmdErr != nil { 184 | p.Send(render.ErrorMsg{}) 185 | } 186 | 187 | time.Sleep(time.Millisecond * 200) 188 | 189 | dockerLoadOutChan, _, sessionErr := utils.RunCommand(sshClient, fmt.Sprintf("cd %s && docker load -i %s && rm %s", appConfig.Name, imgFileName, imgFileName)) 190 | go func() { 191 | p.Send(render.LogMsg{LogLine: <-dockerLoadOutChan + "\n"}) 192 | time.Sleep(time.Millisecond * 50) 193 | }() 194 | if sessionErr != nil { 195 | time.Sleep(time.Millisecond * 100) 196 | p.Send(render.ErrorMsg{ErrorStr: sessionErr.Error()}) 197 | } 198 | 199 | time.Sleep(time.Millisecond * 100) 200 | p.Send(render.NextStageMsg{}) 201 | 202 | previewFolder := fmt.Sprintf("./%s/preview/%s", appConfig.Name, deployHash) 203 | rsyncCmd := exec.Command("rsync", "docker-compose.yaml", fmt.Sprintf("%s@%s:%s", "sidekick", viper.GetString("serverAddress"), previewFolder)) 204 | rsyncCmErr := rsyncCmd.Run() 205 | if rsyncCmErr != nil { 206 | p.Send(render.ErrorMsg{ErrorStr: rsyncCmErr.Error()}) 207 | } 208 | 209 | if appConfig.Env.File != "" { 210 | encryptSync := exec.Command("rsync", "encrypted.env", fmt.Sprintf("%s@%s:%s", "sidekick", viper.GetString("serverAddress"), previewFolder)) 211 | encryptSyncErrr := encryptSync.Run() 212 | if encryptSyncErrr != nil { 213 | p.Send(render.ErrorMsg{ErrorStr: encryptSyncErrr.Error()}) 214 | } 215 | 216 | runAppCmdOutChan, _, sessionErr1 := utils.RunCommand(sshClient, fmt.Sprintf(`cd %s && export SOPS_AGE_KEY=%s && sops exec-env encrypted.env 'docker compose -p sidekick up -d'`, previewFolder, viper.GetString("secretKey"))) 217 | go func() { 218 | p.Send(render.LogMsg{LogLine: <-runAppCmdOutChan + "\n"}) 219 | time.Sleep(time.Millisecond * 50) 220 | }() 221 | if sessionErr1 != nil { 222 | p.Send(render.ErrorMsg{ErrorStr: sessionErr1.Error()}) 223 | } 224 | } else { 225 | runAppCmdOutChan, _, sessionErr1 := utils.RunCommand(sshClient, fmt.Sprintf(`cd %s && docker compose -p sidekick up -d`, previewFolder)) 226 | go func() { 227 | p.Send(render.LogMsg{LogLine: <-runAppCmdOutChan + "\n"}) 228 | time.Sleep(time.Millisecond * 50) 229 | }() 230 | if sessionErr1 != nil { 231 | p.Send(render.ErrorMsg{ErrorStr: sessionErr1.Error()}) 232 | } 233 | } 234 | previewEnvConfig := utils.SidekickPreview{ 235 | Url: fmt.Sprintf("https://%s", previewURL), 236 | Image: imageName, 237 | CreatedAt: time.Now().Format(time.UnixDate), 238 | } 239 | if len(appConfig.PreviewEnvs) == 0 { 240 | appConfig.PreviewEnvs = map[string]utils.SidekickPreview{} 241 | } 242 | appConfig.PreviewEnvs[deployHash] = previewEnvConfig 243 | 244 | ymlData, _ := yaml.Marshal(&appConfig) 245 | os.WriteFile("./sidekick.yml", ymlData, 0644) 246 | 247 | os.Remove("docker-compose.yaml") 248 | os.Remove("encrypted.env") 249 | os.Remove(imgFileName) 250 | 251 | p.Send(render.AllDoneMsg{Duration: time.Since(start).Round(time.Second), URL: previewURL}) 252 | }() 253 | 254 | if _, err := p.Run(); err != nil { 255 | fmt.Println("Error running program:", err) 256 | os.Exit(1) 257 | } 258 | }, 259 | } 260 | 261 | func init() { 262 | PreviewCmd.AddCommand(previewList.ListCmd) 263 | PreviewCmd.AddCommand(previewRemove.RemoveCmd) 264 | } 265 | -------------------------------------------------------------------------------- /cmd/preview/remove/remove.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package previewRemove 16 | 17 | import ( 18 | "fmt" 19 | "os" 20 | 21 | "github.com/charmbracelet/huh" 22 | "github.com/charmbracelet/huh/spinner" 23 | "github.com/charmbracelet/lipgloss" 24 | "github.com/charmbracelet/lipgloss/table" 25 | "github.com/charmbracelet/log" 26 | "github.com/mightymoud/sidekick/render" 27 | "github.com/mightymoud/sidekick/utils" 28 | "github.com/spf13/cobra" 29 | "github.com/spf13/viper" 30 | "gopkg.in/yaml.v3" 31 | ) 32 | 33 | var RemoveCmd = &cobra.Command{ 34 | Use: "remove", 35 | Aliases: []string{"rm"}, 36 | Short: "This command removes a preview environment", 37 | Long: "This command removes a preview environment by the git hash associated with them", 38 | Run: func(cmd *cobra.Command, args []string) { 39 | if configErr := utils.ViperInit(); configErr != nil { 40 | render.GetLogger(log.Options{Prefix: "Sidekick Config"}).Fatal("Not found - Run Sidekick init first") 41 | } 42 | if !utils.FileExists("./sidekick.yml") { 43 | render.GetLogger(log.Options{Prefix: "Project Config"}).Fatal("Not found in current directory Run sidekick launch") 44 | } 45 | 46 | appConfig, appConfigErr := utils.LoadAppConfig() 47 | if appConfigErr != nil { 48 | log.Fatalf("Unable to load your config file. Might be corrupted") 49 | } 50 | 51 | var selected string 52 | var confirm bool 53 | 54 | if len(appConfig.PreviewEnvs) == 0 { 55 | render.GetLogger(log.Options{Prefix: "Preview Envs"}).Info("Not Found in current project") 56 | os.Exit(0) 57 | } 58 | 59 | header := lipgloss.NewStyle().Foreground(lipgloss.Color("77")).MarginTop(1).MarginLeft(1).Render("Currently running preview envs:") 60 | tableString := table.New(). 61 | Border(lipgloss.RoundedBorder()). 62 | BorderStyle(lipgloss.NewStyle().Foreground(lipgloss.Color("99"))). 63 | StyleFunc(func(row, col int) lipgloss.Style { 64 | switch { 65 | case row == 0: 66 | return lipgloss.NewStyle().Foreground(lipgloss.Color("60")).Align(lipgloss.Center) 67 | default: 68 | return lipgloss.NewStyle().Foreground(lipgloss.Color("78")).PaddingLeft(1).PaddingRight(1) 69 | } 70 | }). 71 | Headers("Commit", "Image", "Deployed At", "URL") 72 | 73 | hashSlice := []huh.Option[string]{} 74 | for v := range appConfig.PreviewEnvs { 75 | hashSlice = append(hashSlice, huh.NewOption(v, v)) 76 | tableString.Row(v, appConfig.PreviewEnvs[v].Image, appConfig.PreviewEnvs[v].CreatedAt, appConfig.PreviewEnvs[v].Url) 77 | } 78 | fmt.Println(header) 79 | fmt.Println(tableString) 80 | huh.NewSelect[string](). 81 | Title("Which preview env would you like to delete?"). 82 | Options(hashSlice...). 83 | Value(&selected). 84 | Run() 85 | huh.NewConfirm(). 86 | Title("Are you sure?"). 87 | Affirmative("Yes!"). 88 | Negative("No."). 89 | Value(&confirm). 90 | Run() 91 | if !confirm { 92 | os.Exit(0) 93 | } else { 94 | action := func() { 95 | deletePreviewEnv(selected) 96 | } 97 | spinner.New(). 98 | Title("Deleting your selected preview environment..."). 99 | Action(action). 100 | Run() 101 | 102 | fmt.Println("Preview env deleted successfully!") 103 | } 104 | 105 | }, 106 | } 107 | 108 | func deletePreviewEnv(hash string) { 109 | 110 | appConfig, appConfigErr := utils.LoadAppConfig() 111 | if appConfigErr != nil { 112 | log.Fatalf("Unable to load your config file. Might be corrupted") 113 | } 114 | sshClient, err := utils.Login(viper.GetString("serverAddress"), "sidekick") 115 | if err != nil { 116 | log.Fatal("Unable to login to your VPS") 117 | } 118 | 119 | _, _, dockerDwnErr := utils.RunCommand(sshClient, fmt.Sprintf("cd %s/preview/%s && docker rm -f sidekick-%s-%s-1 && docker image rm %s:%s", appConfig.Name, hash, appConfig.Name, hash, appConfig.Name, hash)) 120 | if dockerDwnErr != nil { 121 | log.Fatalf("Issue happened stopping your service: %s", dockerDwnErr) 122 | } 123 | _, _, folderRmErr := utils.RunCommand(sshClient, fmt.Sprintf("rm -rf %s/preview/%s", appConfig.Name, hash)) 124 | if folderRmErr != nil { 125 | log.Fatalf("Issue happened deleting the preview folder: %s", folderRmErr) 126 | } 127 | 128 | delete(appConfig.PreviewEnvs, hash) 129 | ymlData, _ := yaml.Marshal(&appConfig) 130 | os.WriteFile("./sidekick.yml", ymlData, 0644) 131 | } 132 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package cmd 16 | 17 | import ( 18 | "os" 19 | 20 | "github.com/mightymoud/sidekick/cmd/deploy" 21 | "github.com/mightymoud/sidekick/cmd/launch" 22 | "github.com/mightymoud/sidekick/cmd/preview" 23 | "github.com/spf13/cobra" 24 | ) 25 | 26 | var version = "dev" 27 | 28 | var rootCmd = &cobra.Command{ 29 | Use: "sidekick", 30 | Version: version, 31 | Short: "CLI to self-host all your apps on a single VPS without vendor locking", 32 | Long: `With sidekick you can deploy any number of applications to a single VPS, connect multiple domains and much more.`, 33 | } 34 | 35 | func Execute() { 36 | err := rootCmd.Execute() 37 | if err != nil { 38 | os.Exit(1) 39 | } 40 | } 41 | 42 | func init() { 43 | rootCmd.SetVersionTemplate(`{{println .Version}}`) 44 | rootCmd.AddCommand(preview.PreviewCmd) 45 | rootCmd.AddCommand(deploy.DeployCmd) 46 | rootCmd.AddCommand(launch.LaunchCmd) 47 | } 48 | -------------------------------------------------------------------------------- /demo/imgs/deploy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MightyMoud/sidekick/7713fb29ce3cdcd03f2addf3e2abe9b9a5bf32af/demo/imgs/deploy.png -------------------------------------------------------------------------------- /demo/imgs/hero.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MightyMoud/sidekick/7713fb29ce3cdcd03f2addf3e2abe9b9a5bf32af/demo/imgs/hero.png -------------------------------------------------------------------------------- /demo/imgs/init.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MightyMoud/sidekick/7713fb29ce3cdcd03f2addf3e2abe9b9a5bf32af/demo/imgs/init.png -------------------------------------------------------------------------------- /demo/imgs/launch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MightyMoud/sidekick/7713fb29ce3cdcd03f2addf3e2abe9b9a5bf32af/demo/imgs/launch.png -------------------------------------------------------------------------------- /demo/imgs/preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MightyMoud/sidekick/7713fb29ce3cdcd03f2addf3e2abe9b9a5bf32af/demo/imgs/preview.png -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/mightymoud/sidekick 2 | 3 | go 1.22.4 4 | 5 | require ( 6 | github.com/charmbracelet/bubbles v0.20.0 7 | github.com/charmbracelet/bubbletea v1.1.1 8 | github.com/charmbracelet/lipgloss v0.13.0 9 | github.com/charmbracelet/log v0.4.0 10 | github.com/skeema/knownhosts v1.3.0 11 | github.com/spf13/cobra v1.8.1 12 | github.com/spf13/viper v1.19.0 13 | golang.org/x/crypto v0.24.0 14 | gopkg.in/yaml.v3 v3.0.1 15 | ) 16 | 17 | require ( 18 | atomicgo.dev/cursor v0.2.0 // indirect 19 | atomicgo.dev/keyboard v0.2.9 // indirect 20 | atomicgo.dev/schedule v0.1.0 // indirect 21 | github.com/atotto/clipboard v0.1.4 // indirect 22 | github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect 23 | github.com/catppuccin/go v0.2.0 // indirect 24 | github.com/charmbracelet/x/ansi v0.2.3 // indirect 25 | github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect 26 | github.com/charmbracelet/x/term v0.2.0 // indirect 27 | github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect 28 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect 29 | github.com/dustin/go-humanize v1.0.1 // indirect 30 | github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect 31 | github.com/fsnotify/fsnotify v1.7.0 // indirect 32 | github.com/go-logfmt/logfmt v0.6.0 // indirect 33 | github.com/gookit/color v1.5.4 // indirect 34 | github.com/hashicorp/hcl v1.0.0 // indirect 35 | github.com/joho/godotenv v1.5.1 // indirect 36 | github.com/lithammer/fuzzysearch v1.1.8 // indirect 37 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 38 | github.com/magiconair/properties v1.8.7 // indirect 39 | github.com/mattn/go-isatty v0.0.20 // indirect 40 | github.com/mattn/go-localereader v0.0.1 // indirect 41 | github.com/mattn/go-runewidth v0.0.16 // indirect 42 | github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect 43 | github.com/mitchellh/mapstructure v1.5.0 // indirect 44 | github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect 45 | github.com/muesli/cancelreader v0.2.2 // indirect 46 | github.com/muesli/reflow v0.3.0 // indirect 47 | github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a // indirect 48 | github.com/pelletier/go-toml/v2 v2.2.2 // indirect 49 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect 50 | github.com/rivo/uniseg v0.4.7 // indirect 51 | github.com/sagikazarmark/locafero v0.4.0 // indirect 52 | github.com/sagikazarmark/slog-shim v0.1.0 // indirect 53 | github.com/sourcegraph/conc v0.3.0 // indirect 54 | github.com/spf13/afero v1.11.0 // indirect 55 | github.com/spf13/cast v1.6.0 // indirect 56 | github.com/subosito/gotenv v1.6.0 // indirect 57 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect 58 | go.uber.org/atomic v1.9.0 // indirect 59 | go.uber.org/multierr v1.9.0 // indirect 60 | golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect 61 | golang.org/x/sync v0.8.0 // indirect 62 | golang.org/x/term v0.21.0 // indirect 63 | golang.org/x/text v0.18.0 // indirect 64 | gopkg.in/ini.v1 v1.67.0 // indirect 65 | ) 66 | 67 | require ( 68 | github.com/charmbracelet/huh v0.6.0 69 | github.com/charmbracelet/huh/spinner v0.0.0-20241011224433-983a50776b31 70 | github.com/erikgeiser/promptkit v0.9.0 71 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 72 | github.com/pterm/pterm v0.12.79 73 | github.com/spf13/pflag v1.0.5 // indirect 74 | github.com/stretchr/testify v1.9.0 75 | golang.org/x/sys v0.25.0 // indirect 76 | ) 77 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | atomicgo.dev/assert v0.0.2 h1:FiKeMiZSgRrZsPo9qn/7vmr7mCsh5SZyXY4YGYiYwrg= 2 | atomicgo.dev/assert v0.0.2/go.mod h1:ut4NcI3QDdJtlmAxQULOmA13Gz6e2DWbSAS8RUOmNYQ= 3 | atomicgo.dev/cursor v0.2.0 h1:H6XN5alUJ52FZZUkI7AlJbUc1aW38GWZalpYRPpoPOw= 4 | atomicgo.dev/cursor v0.2.0/go.mod h1:Lr4ZJB3U7DfPPOkbH7/6TOtJ4vFGHlgj1nc+n900IpU= 5 | atomicgo.dev/keyboard v0.2.9 h1:tOsIid3nlPLZ3lwgG8KZMp/SFmr7P0ssEN5JUsm78K8= 6 | atomicgo.dev/keyboard v0.2.9/go.mod h1:BC4w9g00XkxH/f1HXhW2sXmJFOCWbKn9xrOunSFtExQ= 7 | atomicgo.dev/schedule v0.1.0 h1:nTthAbhZS5YZmgYbb2+DH8uQIZcTlIrd4eYr3UQxEjs= 8 | atomicgo.dev/schedule v0.1.0/go.mod h1:xeUa3oAkiuHYh8bKiQBRojqAMq3PXXbJujjb0hw8pEU= 9 | github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= 10 | github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= 11 | github.com/MarvinJWendt/testza v0.1.0/go.mod h1:7AxNvlfeHP7Z/hDQ5JtE3OKYT3XFUeLCDE2DQninSqs= 12 | github.com/MarvinJWendt/testza v0.2.1/go.mod h1:God7bhG8n6uQxwdScay+gjm9/LnO4D3kkcZX4hv9Rp8= 13 | github.com/MarvinJWendt/testza v0.2.8/go.mod h1:nwIcjmr0Zz+Rcwfh3/4UhBp7ePKVhuBExvZqnKYWlII= 14 | github.com/MarvinJWendt/testza v0.2.10/go.mod h1:pd+VWsoGUiFtq+hRKSU1Bktnn+DMCSrDrXDpX2bG66k= 15 | github.com/MarvinJWendt/testza v0.2.12/go.mod h1:JOIegYyV7rX+7VZ9r77L/eH6CfJHHzXjB69adAhzZkI= 16 | github.com/MarvinJWendt/testza v0.3.0/go.mod h1:eFcL4I0idjtIx8P9C6KkAuLgATNKpX4/2oUqKc6bF2c= 17 | github.com/MarvinJWendt/testza v0.4.2/go.mod h1:mSdhXiKH8sg/gQehJ63bINcCKp7RtYewEjXsvsVUPbE= 18 | github.com/MarvinJWendt/testza v0.5.2 h1:53KDo64C1z/h/d/stCYCPY69bt/OSwjq5KpFNwi+zB4= 19 | github.com/MarvinJWendt/testza v0.5.2/go.mod h1:xu53QFE5sCdjtMCKk8YMQ2MnymimEctc4n3EjyIYvEY= 20 | github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk= 21 | github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= 22 | github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= 23 | github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= 24 | github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= 25 | github.com/aymanbagabas/go-udiff v0.2.0 h1:TK0fH4MteXUDspT88n8CKzvK0X9O2xu9yQjWpi6yML8= 26 | github.com/aymanbagabas/go-udiff v0.2.0/go.mod h1:RE4Ex0qsGkTAJoQdQQCA0uG+nAzJO/pI/QwceO5fgrA= 27 | github.com/catppuccin/go v0.2.0 h1:ktBeIrIP42b/8FGiScP9sgrWOss3lw0Z5SktRoithGA= 28 | github.com/catppuccin/go v0.2.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc= 29 | github.com/charmbracelet/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE= 30 | github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU= 31 | github.com/charmbracelet/bubbletea v1.1.1 h1:KJ2/DnmpfqFtDNVTvYZ6zpPFL9iRCRr0qqKOCvppbPY= 32 | github.com/charmbracelet/bubbletea v1.1.1/go.mod h1:9Ogk0HrdbHolIKHdjfFpyXJmiCzGwy+FesYkZr7hYU4= 33 | github.com/charmbracelet/huh v0.6.0 h1:mZM8VvZGuE0hoDXq6XLxRtgfWyTI3b2jZNKh0xWmax8= 34 | github.com/charmbracelet/huh v0.6.0/go.mod h1:GGNKeWCeNzKpEOh/OJD8WBwTQjV3prFAtQPpLv+AVwU= 35 | github.com/charmbracelet/huh/spinner v0.0.0-20241011224433-983a50776b31 h1:HqaYBKXy1eQBnN9tCLJJHaQ+3btqonOVh25LZ/Xaxps= 36 | github.com/charmbracelet/huh/spinner v0.0.0-20241011224433-983a50776b31/go.mod h1:Cxhgl8N0sX9A+EQxedzzGZAalaF8fUVL+JP/pSOW8cI= 37 | github.com/charmbracelet/lipgloss v0.13.0 h1:4X3PPeoWEDCMvzDvGmTajSyYPcZM4+y8sCA/SsA3cjw= 38 | github.com/charmbracelet/lipgloss v0.13.0/go.mod h1:nw4zy0SBX/F/eAO1cWdcvy6qnkDUxr8Lw7dvFrAIbbY= 39 | github.com/charmbracelet/log v0.4.0 h1:G9bQAcx8rWA2T3pWvx7YtPTPwgqpk7D68BX21IRW8ZM= 40 | github.com/charmbracelet/log v0.4.0/go.mod h1:63bXt/djrizTec0l11H20t8FDSvA4CRZJ1KH22MdptM= 41 | github.com/charmbracelet/x/ansi v0.2.3 h1:VfFN0NUpcjBRd4DnKfRaIRo53KRgey/nhOoEqosGDEY= 42 | github.com/charmbracelet/x/ansi v0.2.3/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= 43 | github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b h1:MnAMdlwSltxJyULnrYbkZpp4k58Co7Tah3ciKhSNo0Q= 44 | github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= 45 | github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4= 46 | github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ= 47 | github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0= 48 | github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0= 49 | github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= 50 | github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY= 51 | github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk= 52 | github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 53 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 54 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 55 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= 56 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 57 | github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= 58 | github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= 59 | github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= 60 | github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= 61 | github.com/erikgeiser/promptkit v0.9.0 h1:3qL1mS/ntCrXdb8sTP/ka82CJ9kEQaGuYXNrYJkWYBc= 62 | github.com/erikgeiser/promptkit v0.9.0/go.mod h1:pU9dtogSe3Jlc2AY77EP7R4WFP/vgD4v+iImC83KsCo= 63 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= 64 | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= 65 | github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= 66 | github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= 67 | github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= 68 | github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= 69 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= 70 | github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 71 | github.com/gookit/color v1.4.2/go.mod h1:fqRyamkC1W8uxl+lxCQxOT09l/vYfZ+QeiX3rKQHCoQ= 72 | github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo= 73 | github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= 74 | github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= 75 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= 76 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= 77 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 78 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 79 | github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= 80 | github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= 81 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 82 | github.com/klauspost/cpuid/v2 v2.0.10/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= 83 | github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= 84 | github.com/klauspost/cpuid/v2 v2.2.3 h1:sxCkb+qR91z4vsqw4vGGZlDgPz3G7gjaLyK3V8y70BU= 85 | github.com/klauspost/cpuid/v2 v2.2.3/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= 86 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 87 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 88 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 89 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 90 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 91 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 92 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 93 | github.com/lithammer/fuzzysearch v1.1.8 h1:/HIuJnjHuXS8bKaiTMeeDlW2/AyIWk2brx1V8LFgLN4= 94 | github.com/lithammer/fuzzysearch v1.1.8/go.mod h1:IdqeyBClc3FFqSzYq/MXESsS4S0FsZ5ajtkr5xPLts4= 95 | github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= 96 | github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 97 | github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= 98 | github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= 99 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 100 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 101 | github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= 102 | github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= 103 | github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= 104 | github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 105 | github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= 106 | github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 107 | github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4= 108 | github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE= 109 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= 110 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 111 | github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= 112 | github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= 113 | github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= 114 | github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= 115 | github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= 116 | github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= 117 | github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a h1:2MaM6YC3mGu54x+RKAA6JiFFHlHDY1UbkxqppT7wYOg= 118 | github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a/go.mod h1:hxSnBBYLK21Vtq/PHd0S2FYCxBXzBua8ov5s1RobyRQ= 119 | github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= 120 | github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= 121 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 122 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= 123 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 124 | github.com/pterm/pterm v0.12.27/go.mod h1:PhQ89w4i95rhgE+xedAoqous6K9X+r6aSOI2eFF7DZI= 125 | github.com/pterm/pterm v0.12.29/go.mod h1:WI3qxgvoQFFGKGjGnJR849gU0TsEOvKn5Q8LlY1U7lg= 126 | github.com/pterm/pterm v0.12.30/go.mod h1:MOqLIyMOgmTDz9yorcYbcw+HsgoZo3BQfg2wtl3HEFE= 127 | github.com/pterm/pterm v0.12.31/go.mod h1:32ZAWZVXD7ZfG0s8qqHXePte42kdz8ECtRyEejaWgXU= 128 | github.com/pterm/pterm v0.12.33/go.mod h1:x+h2uL+n7CP/rel9+bImHD5lF3nM9vJj80k9ybiiTTE= 129 | github.com/pterm/pterm v0.12.36/go.mod h1:NjiL09hFhT/vWjQHSj1athJpx6H8cjpHXNAK5bUw8T8= 130 | github.com/pterm/pterm v0.12.40/go.mod h1:ffwPLwlbXxP+rxT0GsgDTzS3y3rmpAO1NMjUkGTYf8s= 131 | github.com/pterm/pterm v0.12.79 h1:lH3yrYMhdpeqX9y5Ep1u7DejyHy7NSQg9qrBjF9dFT4= 132 | github.com/pterm/pterm v0.12.79/go.mod h1:1v/gzOF1N0FsjbgTHZ1wVycRkKiatFvJSJC4IGaQAAo= 133 | github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 134 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 135 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= 136 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 137 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= 138 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 139 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 140 | github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= 141 | github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= 142 | github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= 143 | github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= 144 | github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= 145 | github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= 146 | github.com/skeema/knownhosts v1.3.0 h1:AM+y0rI04VksttfwjkSTNQorvGqmwATnvnAHpSgc0LY= 147 | github.com/skeema/knownhosts v1.3.0/go.mod h1:sPINvnADmT/qYH1kfv+ePMmOBTH6Tbl7b5LvTDjFK7M= 148 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= 149 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= 150 | github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= 151 | github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= 152 | github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= 153 | github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= 154 | github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= 155 | github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= 156 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 157 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 158 | github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= 159 | github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= 160 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 161 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 162 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 163 | github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= 164 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 165 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 166 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 167 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 168 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 169 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 170 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 171 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 172 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 173 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= 174 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= 175 | github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= 176 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= 177 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= 178 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 179 | go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= 180 | go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= 181 | go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= 182 | go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= 183 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 184 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 185 | golang.org/x/crypto v0.24.0 h1:mnl8DM0o513X8fdIkmyFE/5hTYxbwYOjDS/+rK6qpRI= 186 | golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= 187 | golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= 188 | golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= 189 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 190 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 191 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 192 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 193 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 194 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 195 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 196 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 197 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 198 | golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= 199 | golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 200 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 201 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 202 | golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 203 | golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 204 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 205 | golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 206 | golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 207 | golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 208 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 209 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 210 | golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 211 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 212 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 213 | golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= 214 | golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 215 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 216 | golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 217 | golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 218 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 219 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 220 | golang.org/x/term v0.21.0 h1:WVXCp+/EBEHOj53Rvu+7KiT/iElMrO8ACK16SMZ3jaA= 221 | golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0= 222 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 223 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 224 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 225 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 226 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 227 | golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= 228 | golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= 229 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 230 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 231 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 232 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 233 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 234 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 235 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= 236 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 237 | gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= 238 | gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= 239 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 240 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 241 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 242 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 243 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 244 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 245 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package main 16 | 17 | import "github.com/mightymoud/sidekick/cmd" 18 | 19 | func main() { 20 | cmd.Execute() 21 | } 22 | -------------------------------------------------------------------------------- /render/tui.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package render 16 | 17 | import ( 18 | "bufio" 19 | "io" 20 | "time" 21 | 22 | "github.com/charmbracelet/bubbles/spinner" 23 | tea "github.com/charmbracelet/bubbletea" 24 | "github.com/charmbracelet/lipgloss" 25 | "github.com/charmbracelet/lipgloss/tree" 26 | ) 27 | 28 | var ( 29 | spinnerStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("63")).MarginRight(1).MarginLeft(1) 30 | successStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#04B575")).MarginLeft(1) 31 | cancelStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("220")).Faint(true).MarginLeft(1) 32 | errorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#FF0000")).MarginLeft(1) 33 | pendingStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240")).MarginLeft(1) 34 | allDoneStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("69")).MarginTop(1).MarginLeft(1).MarginBottom(1) 35 | appStyle = lipgloss.NewStyle() 36 | ) 37 | 38 | func (m TuiModel) Init() tea.Cmd { 39 | return m.Stages[m.ActiveIndex].Spinner.Tick 40 | } 41 | 42 | func (m TuiModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { 43 | switch msg := msg.(type) { 44 | 45 | case tea.KeyMsg: 46 | m.Quitting = true 47 | 48 | return m, tea.Quit 49 | 50 | case tea.WindowSizeMsg: 51 | m.ViewportHeight = msg.Height 52 | m.ViewportWidth = msg.Width 53 | return m, nil 54 | 55 | case LogMsg: 56 | logStage := m.Stages[m.ActiveIndex] 57 | logStage.Logs = append(logStage.Logs, msg.LogLine) 58 | m.Stages[m.ActiveIndex] = logStage 59 | 60 | return m, nil 61 | 62 | case ErrorMsg: 63 | logStage := m.Stages[m.ActiveIndex] 64 | logStage.HasError = true 65 | if msg.ErrorStr != "" { 66 | logStage.Logs = append(logStage.Logs, msg.ErrorStr) 67 | } 68 | m.Stages[m.ActiveIndex] = logStage 69 | 70 | return m, tea.Quit 71 | 72 | case NextStageMsg: 73 | m.ActiveIndex = m.ActiveIndex + 1 74 | 75 | return m, m.Stages[m.ActiveIndex].Spinner.Tick 76 | 77 | case AllDoneMsg: 78 | m.AllDone = true 79 | m.URL = msg.URL 80 | m.Duration = msg.Duration 81 | 82 | return m, tea.Quit 83 | 84 | case spinner.TickMsg: 85 | var cmd tea.Cmd 86 | m.Stages[m.ActiveIndex].Spinner, cmd = m.Stages[m.ActiveIndex].Spinner.Update(msg) 87 | return m, cmd 88 | default: 89 | return m, nil 90 | } 91 | } 92 | 93 | func (m TuiModel) View() string { 94 | var s string 95 | printSlice := []string{} 96 | 97 | printSlice = append(printSlice, getBannerStyle(m).Render(m.BannerMsg)) 98 | 99 | var logs string 100 | for _, res := range m.Stages[m.ActiveIndex].Logs { 101 | logs += res 102 | } 103 | 104 | for index, stage := range m.Stages { 105 | if !m.AllDone { 106 | if index < m.ActiveIndex { 107 | printSlice = append(printSlice, successStyle.Render("✔ "+stage.Success)) 108 | } else if index == m.ActiveIndex { 109 | if !stage.HasError { 110 | printSlice = append(printSlice, stage.Spinner.View()+stage.Title) 111 | } else { 112 | u := tree.Root("⚠ " + stage.Title).Child(stage.Logs) 113 | printSlice = append(printSlice, errorStyle.Render(u.String())) 114 | } 115 | if stage.HasLogs && !stage.HasError { 116 | var t string 117 | if !stage.HasError { 118 | l := len(stage.Logs) 119 | if l < 5 { 120 | t = getLogContainerStyle(m).Render(stage.Logs...) 121 | } else { 122 | t = getLogContainerStyle(m).Render(stage.Logs[l-5:]...) 123 | } 124 | } else { 125 | t = getLogContainerStyle(m).Render(stage.Logs...) 126 | } 127 | printSlice = append(printSlice, t) 128 | } 129 | } else if index > m.ActiveIndex { 130 | var text string 131 | if m.Quitting { 132 | text = cancelStyle.Render("CANCELLED " + stage.Title) 133 | } else { 134 | text = pendingStyle.Render("󰚭 " + stage.Title) 135 | } 136 | printSlice = append(printSlice, pendingStyle.Render(text)) 137 | } 138 | } else { 139 | printSlice = append(printSlice, successStyle.Render("✔ "+stage.Success)) 140 | } 141 | } 142 | 143 | if m.AllDone { 144 | printSlice = append(printSlice, allDoneStyle.Render("🚀 Deployed successfully in "+m.Duration.String()+".\n"+"😎 View your app at https://"+m.URL)) 145 | } 146 | 147 | s += lipgloss.JoinVertical(lipgloss.Top, printSlice...) 148 | 149 | s += "\n" 150 | 151 | if m.Quitting { 152 | s += "\n" 153 | } 154 | 155 | return appStyle.Render(s) 156 | } 157 | 158 | func getLogContainerStyle(m TuiModel) lipgloss.Style { 159 | return lipgloss. 160 | NewStyle(). 161 | Width(int(0.8 * float64(m.ViewportWidth))). 162 | Height(0). 163 | MarginLeft(1). 164 | BorderStyle(lipgloss.RoundedBorder()). 165 | BorderForeground(lipgloss.Color("69")). 166 | Foreground(lipgloss.Color("white")).Faint(true) 167 | } 168 | func getBannerStyle(m TuiModel) lipgloss.Style { 169 | return lipgloss.NewStyle(). 170 | Foreground(lipgloss.Color("white")). 171 | Background(lipgloss.Color("#414868")). 172 | Width(m.ViewportWidth). 173 | Padding(1). 174 | Align(lipgloss.Center). 175 | MarginBottom(1). 176 | MarginTop(1) 177 | } 178 | 179 | func MakeStage(title string, success string, hasLogs bool) Stage { 180 | s := spinner.New() 181 | s.Style = spinnerStyle 182 | s.Spinner = spinner.MiniDot 183 | 184 | logs := []string{} 185 | 186 | return Stage{ 187 | Spinner: s, 188 | Title: title, 189 | Success: success, 190 | Logs: logs, 191 | HasLogs: hasLogs, 192 | } 193 | } 194 | 195 | func SendLogsToTUI(source io.ReadCloser, p *tea.Program) { 196 | scanner := bufio.NewScanner(source) 197 | for scanner.Scan() { 198 | line := scanner.Text() 199 | if line != "\n" { 200 | p.Send(LogMsg{LogLine: scanner.Text() + "\n"}) 201 | time.Sleep(time.Millisecond * 50) 202 | } 203 | } 204 | } 205 | -------------------------------------------------------------------------------- /render/types.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package render 16 | 17 | import ( 18 | "time" 19 | 20 | "github.com/charmbracelet/bubbles/spinner" 21 | tea "github.com/charmbracelet/bubbletea" 22 | ) 23 | 24 | type LogMsg struct { 25 | LogLine string 26 | } 27 | 28 | type AllDoneMsg struct { 29 | Duration time.Duration 30 | URL string 31 | } 32 | 33 | type ErrorMsg struct { 34 | ErrorStr string 35 | } 36 | type NextStageMsg struct{} 37 | 38 | type Stage struct { 39 | Title string 40 | Success string 41 | Spinner spinner.Model 42 | Logs []string 43 | HasLogs bool 44 | HasError bool 45 | } 46 | 47 | type TuiModel struct { 48 | tea.Model 49 | ActiveIndex int 50 | Stages []Stage 51 | Quitting bool 52 | ViewportWidth int 53 | ViewportHeight int 54 | AllDone bool 55 | Duration time.Duration 56 | URL string 57 | BannerMsg string 58 | } 59 | -------------------------------------------------------------------------------- /render/utils.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package render 16 | 17 | import ( 18 | "fmt" 19 | "os" 20 | "time" 21 | 22 | "github.com/charmbracelet/lipgloss" 23 | "github.com/charmbracelet/log" 24 | "github.com/erikgeiser/promptkit/textinput" 25 | "github.com/pterm/pterm" 26 | "github.com/pterm/pterm/putils" 27 | ) 28 | 29 | func getDefaultTextInput(prompt string, defaultValue string, placeholder string) *textinput.TextInput { 30 | inputPrompt := fmt.Sprintf("%s: ", prompt) 31 | 32 | if defaultValue != "" { 33 | inputPrompt = fmt.Sprintf("%s \033[3m(default: %s)\033[0m: ", prompt, defaultValue) 34 | } 35 | 36 | input := textinput.New(inputPrompt) 37 | input.Placeholder = placeholder 38 | input.InitialValue = "" 39 | 40 | input.InputTextStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("120")) 41 | 42 | if defaultValue != "" { 43 | input.Validate = nil 44 | } 45 | 46 | return input 47 | } 48 | 49 | func GenerateTextQuestion(question string, defaultAnswer string, placeholder string) string { 50 | input := getDefaultTextInput(question, defaultAnswer, placeholder) 51 | userAnswer, err := input.RunPrompt() 52 | 53 | if err != nil { 54 | GetLogger(log.Options{Prefix: "Input"}).Fatalf(" %s", err) 55 | } 56 | 57 | if defaultAnswer != "" && userAnswer == "" { 58 | return defaultAnswer 59 | } 60 | 61 | return userAnswer 62 | } 63 | 64 | func GetLogger(options log.Options) *log.Logger { 65 | options.ReportCaller = false 66 | options.ReportTimestamp = true 67 | options.TimeFormat = time.Kitchen 68 | 69 | return log.NewWithOptions(os.Stderr, options) 70 | } 71 | 72 | func RenderSidekickBig() { 73 | pterm.Println() 74 | 75 | s, _ := pterm.DefaultBigText.WithLetters( 76 | putils.LettersFromStringWithStyle("Side", pterm.FgCyan.ToStyle()), 77 | putils.LettersFromStringWithStyle("kick", pterm.FgLightMagenta.ToStyle())).Srender() 78 | pterm.DefaultCenter.Println(s) 79 | 80 | } 81 | 82 | func RenderKeyValidation(resultLines []string, keyHash string, hostname string) { 83 | startColor := pterm.NewRGB(0, 255, 255) 84 | endColor := pterm.NewRGB(255, 0, 255) 85 | 86 | pterm.DefaultCenter.Print(keyHash) 87 | for i := 0; i < len(resultLines[1:]); i++ { 88 | fadeFactor := float32(i) / float32(20) 89 | currentColor := startColor.Fade(0, 1, fadeFactor, endColor) 90 | pterm.DefaultCenter.Print(currentColor.Sprint(resultLines[1:][i])) 91 | } 92 | prompt := pterm.DefaultInteractiveContinue 93 | 94 | pterm.DefaultCenter.Printf(pterm.FgYellow.Sprintf("This is the ASCII art and fingerprint of your VPS's public key at %s", hostname)) 95 | pterm.DefaultCenter.Printf(pterm.FgYellow.Sprint("Please confirm you want to continue with the connection")) 96 | pterm.DefaultCenter.Printf(pterm.FgYellow.Sprint("Sidekick will add this host/key pair to known_hosts")) 97 | pterm.Println() 98 | 99 | prompt.DefaultText = "Would you like to proceed?" 100 | prompt.Options = []string{"yes", "no"} 101 | if result, _ := prompt.Show(); result != "yes" { 102 | pterm.Error.Println("In order to continue, you need to accept this.") 103 | os.Exit(0) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /utils/auth.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "log" 7 | "net" 8 | "os" 9 | "os/exec" 10 | "os/user" 11 | "path" 12 | "strings" 13 | "time" 14 | 15 | "github.com/mightymoud/sidekick/render" 16 | "github.com/skeema/knownhosts" 17 | "golang.org/x/crypto/ssh" 18 | "golang.org/x/crypto/ssh/agent" 19 | ) 20 | 21 | func getKeyFilesAuth() ([]ssh.AuthMethod, error) { 22 | user, err := user.Current() 23 | if err != nil { 24 | return nil, err 25 | } 26 | sshDir := path.Join(user.HomeDir, ".ssh") 27 | keyFiles := []string{ 28 | "id_rsa", 29 | "id_ecdsa", 30 | "id_ed25519", 31 | } 32 | 33 | var authMethods []ssh.AuthMethod 34 | 35 | for _, keyFile := range keyFiles { 36 | keyPath := path.Join(sshDir, keyFile) 37 | if _, err := os.Stat(keyPath); os.IsNotExist(err) { 38 | continue 39 | } 40 | 41 | privateKey, err := os.ReadFile(keyPath) 42 | if err != nil { 43 | continue 44 | } 45 | 46 | signer, err := ssh.ParsePrivateKey(privateKey) 47 | if err != nil { 48 | continue 49 | } 50 | 51 | authMethods = append(authMethods, ssh.PublicKeys(signer)) 52 | } 53 | 54 | return authMethods, nil 55 | } 56 | 57 | func inspectServerPublicKey(key ssh.PublicKey, hostname string) { 58 | sshKeyCmd := exec.Command("sh", "-s", "-", string(ssh.MarshalAuthorizedKey(key))) 59 | sshKeyCmd.Stdin = strings.NewReader(sshKeyScript) 60 | result, sshKeyCmdErr := sshKeyCmd.Output() 61 | if sshKeyCmdErr != nil { 62 | panic(sshKeyCmdErr) 63 | } 64 | resultLines := strings.Split(string(result), "\n") 65 | keyHash := resultLines[0] 66 | 67 | render.RenderKeyValidation(resultLines, keyHash, hostname) 68 | 69 | } 70 | 71 | func GetSshClient(server string, sshUser string) (*ssh.Client, error) { 72 | sshPort := "22" 73 | sshAgentSock := os.Getenv("SSH_AUTH_SOCK") 74 | if sshAgentSock == "" { 75 | log.Fatal("No SSH SOCK AVAILABLE") 76 | return nil, errors.New("Error happened connecting to ssh-agent") 77 | } 78 | 79 | conn, err := net.Dial("unix", sshAgentSock) 80 | if err != nil { 81 | return nil, err 82 | } 83 | defer conn.Close() 84 | 85 | agentClient := agent.NewClient(conn) 86 | 87 | // Get auth of standard keys not in agent 88 | authMethods, _ := getKeyFilesAuth() 89 | 90 | authMethods = append(authMethods, ssh.PublicKeysCallback(agentClient.Signers)) 91 | 92 | cb := ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { 93 | currentUser, _ := user.Current() 94 | khPath := fmt.Sprintf("%s/.ssh/known_hosts", currentUser.HomeDir) 95 | kh, knErr := knownhosts.NewDB(khPath) 96 | if knErr != nil { 97 | return knErr 98 | } 99 | 100 | innerCallback := kh.HostKeyCallback() 101 | err := innerCallback(hostname, remote, key) 102 | if knownhosts.IsHostKeyChanged(err) { 103 | return fmt.Errorf("REMOTE HOST IDENTIFICATION HAS CHANGED for host %s! This may indicate a MitM attack.", hostname) 104 | } else if knownhosts.IsHostUnknown(err) { 105 | inspectServerPublicKey(key, hostname) 106 | f, ferr := os.OpenFile(khPath, os.O_APPEND|os.O_WRONLY, 0600) 107 | if ferr == nil { 108 | defer f.Close() 109 | ferr = knownhosts.WriteKnownHost(f, hostname, remote, key) 110 | } else { 111 | log.Printf("Failed to add host %s to known_hosts: %v\n", hostname, ferr) 112 | } 113 | return nil 114 | } 115 | return err 116 | }) 117 | 118 | var client *ssh.Client 119 | 120 | // This error will be thrown when one method/key doesn't work 121 | var expectedClientErr = errors.New("ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain") 122 | for _, method := range authMethods { 123 | config := &ssh.ClientConfig{ 124 | User: sshUser, 125 | Auth: []ssh.AuthMethod{method}, 126 | HostKeyCallback: cb, 127 | Timeout: 1 * time.Second, 128 | } 129 | 130 | workingClient, sshClientErr := ssh.Dial("tcp", fmt.Sprintf("%s:%s", server, sshPort), config) 131 | if sshClientErr != nil { 132 | if sshClientErr.Error() != expectedClientErr.Error() { 133 | log.Fatalf("Failed to create ssh client to the server: %v", sshClientErr) 134 | } 135 | continue 136 | } 137 | client = workingClient 138 | break 139 | } 140 | if client == nil { 141 | return nil, errors.New("Logging in failed with all available keys for the said user") 142 | } 143 | return client, nil 144 | } 145 | 146 | func Login(server string, user string) (*ssh.Client, error) { 147 | sshClient, err := GetSshClient(server, user) 148 | if err != nil { 149 | return nil, err 150 | } 151 | return sshClient, nil 152 | } 153 | -------------------------------------------------------------------------------- /utils/scripts.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package utils 16 | 17 | var sshKeyScript = ` 18 | publicKey=$1 19 | 20 | echo "$publicKey" | ssh-keygen -lvf /dev/stdin 21 | ` 22 | 23 | var EnvEncryptionScript = ` 24 | PUBKEY=$1 25 | ENVFILE=$2 26 | 27 | sops encrypt --output-type dotenv --age $PUBKEY $ENVFILE > encrypted.env 28 | ` 29 | 30 | var DeployAppWithEnvScript = ` 31 | export SOPS_AGE_KEY=$age_secret_key && \ 32 | cd $service_name && \ 33 | old_container_id=$(docker ps -f name=$service_name -q | tail -n1) && \ 34 | sops exec-env encrypted.env 'docker compose -p sidekick up -d --no-deps --scale $service_name=2 --no-recreate $service_name' && \ 35 | new_container_id=$(docker ps -f name=$service_name -q | head -n1) && \ 36 | new_container_ip=$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $new_container_id) && \ 37 | curl --silent --include --retry-connrefused --retry 30 --retry-delay 1 --fail http://$new_container_ip:$app_port/up || exit 1 && \ 38 | docker stop $old_container_id && \ 39 | docker rm $old_container_id && \ 40 | sops exec-env encrypted.env 'docker compose -p sidekick up -d --scale $service_name=1 --no-recreate $service_name' 41 | ` 42 | 43 | var DeployAppScript = ` 44 | cd $service_name && \ 45 | old_container_id=$(docker ps -f name=$service_name -q | tail -n1) && \ 46 | docker compose -p sidekick up -d --no-deps --scale $service_name=2 --no-recreate $service_name && \ 47 | new_container_id=$(docker ps -f name=$service_name -q | head -n1) && \ 48 | new_container_ip=$(docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $new_container_id) && \ 49 | curl --silent --include --retry-connrefused --retry 30 --retry-delay 1 --fail http://$new_container_ip:$app_port/up || exit 1 && \ 50 | docker stop $old_container_id && \ 51 | docker rm $old_container_id && \ 52 | docker compose -p sidekick up -d --scale $service_name=1 --no-recreate $service_name 53 | ` 54 | 55 | var CheckGitTreeScript = ` 56 | if [[ -z $(git status -s) ]] 57 | then 58 | echo "all good" 59 | else 60 | echo "tree is dirty, please commit changes before running this" 61 | exit 62 | fi 63 | ` 64 | -------------------------------------------------------------------------------- /utils/spinner.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package utils 16 | 17 | import ( 18 | "github.com/pterm/pterm" 19 | ) 20 | 21 | var stagedSpinner = pterm.DefaultSpinner 22 | 23 | func GetSpinner() pterm.SpinnerPrinter { 24 | stagedSpinner.Sequence = []string{"."} 25 | stagedSpinner.ShowTimer = false 26 | return stagedSpinner 27 | } 28 | -------------------------------------------------------------------------------- /utils/stages.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package utils 16 | 17 | import "fmt" 18 | 19 | var UsersetupStage = CommandsStage{ 20 | SpinnerSuccessMessage: "New user created successfully", 21 | SpinnerFailMessage: "Error creating a new user for the machine", 22 | Commands: []string{ 23 | "sudo useradd -m -s /bin/bash -G sudo sidekick", 24 | `echo "sidekick ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/sidekick`, 25 | "mkdir -p /home/sidekick/.ssh/", 26 | "sudo cat /root/.ssh/authorized_keys | sudo tee -a /home/sidekick/.ssh/authorized_keys", 27 | "sudo chown sidekick:sidekick /home/sidekick/.ssh/authorized_keys", 28 | "sudo chmod 600 /home/sidekick/.ssh/authorized_keys", 29 | }, 30 | } 31 | 32 | var SetupStage = CommandsStage{ 33 | SpinnerSuccessMessage: "VPS updated and setup successfully", 34 | SpinnerFailMessage: "Error happened running basic setup commands", 35 | Commands: []string{ 36 | "sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config && sudo systemctl restart ssh", 37 | "sudo apt-get update -y", 38 | "sudo apt-get upgrade -y", 39 | "sudo apt-get install age -y", 40 | "sudo apt-get install ca-certificates curl vim -y", 41 | "curl -LO https://github.com/getsops/sops/releases/download/v3.9.0/sops-v3.9.0.linux.amd64", 42 | "sudo mv sops-v3.9.0.linux.amd64 /usr/local/bin/sops", 43 | "sudo chmod +x /usr/local/bin/sops", 44 | }, 45 | } 46 | 47 | var DockerStage = CommandsStage{ 48 | SpinnerSuccessMessage: "Docker setup successfully", 49 | SpinnerFailMessage: "Error happened during setting up docker", 50 | Commands: []string{ 51 | "sudo apt-get update -y", 52 | "sudo install -m 0755 -d /etc/apt/keyrings", 53 | "sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc", 54 | "sudo chmod a+r /etc/apt/keyrings/docker.asc", 55 | `echo \ 56 | "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \ 57 | $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \ 58 | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null`, 59 | "sudo apt-get update -y", 60 | "sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -y", 61 | "sudo usermod -aG docker sidekick", 62 | }, 63 | } 64 | 65 | func GetTraefikStage(email string) CommandsStage { 66 | return CommandsStage{ 67 | SpinnerSuccessMessage: "Successfully setup Traefik", 68 | SpinnerFailMessage: "Something went wrong setting up Traefik on your VPS", 69 | Commands: []string{ 70 | "sudo apt-get install git -y", 71 | "git clone https://github.com/mightymoud/sidekick-traefik.git", 72 | fmt.Sprintf(`cd sidekick-traefik/traefik && sed -i.bak 's/\$EMAIL/%s/g' traefik.yml && rm traefik.yml.bak`, email), 73 | "sudo docker network create sidekick", 74 | "cd sidekick-traefik && sudo docker compose -p sidekick up -d", 75 | }, 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /utils/types.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package utils 16 | 17 | type DependsOn struct { 18 | Condition string `yaml:"condition"` 19 | } 20 | 21 | type Healthcheck struct { 22 | Test []string `yaml:"test"` 23 | Interval string `yaml:"interval"` 24 | Timeout string `yaml:"timeout"` 25 | Retries int `yaml:"retries"` 26 | } 27 | 28 | type DockerService struct { 29 | Image string `yaml:"image"` 30 | Command string `yaml:"command,omitempty"` 31 | Restart string `yaml:"restart,omitempty"` 32 | Ports []string `yaml:"ports,omitempty"` 33 | Volumes []string `yaml:"volumes,omitempty"` 34 | Labels []string `yaml:"labels,omitempty"` 35 | Networks []string `yaml:"networks,omitempty"` 36 | Environment []string `yaml:"environment,omitempty"` 37 | DependsOn map[string]DependsOn `yaml:"depends_on,omitempty"` 38 | HealthCheck Healthcheck `yaml:"healthcheck,omitempty"` 39 | EntryPoint []string `yaml:"entrypoint,omitempty"` 40 | } 41 | 42 | type DockerNetwork struct { 43 | External bool `yaml:"external"` 44 | } 45 | 46 | type DockerComposeFile struct { 47 | Services map[string]DockerService `yaml:"services"` 48 | Networks map[string]DockerNetwork `yaml:"networks,omitempty"` 49 | Volumes map[string]DockerVolume `yaml:"volumes,omitempty"` 50 | } 51 | 52 | type DockerVolume struct { 53 | Driver string `yaml:"driver,omitempty"` 54 | } 55 | type SidekickAppEnvConfig struct { 56 | File string `yaml:"file"` 57 | Hash string `yaml:"hash"` 58 | } 59 | 60 | type SidekickPreview struct { 61 | Url string `yaml:"url"` 62 | Image string `yaml:"image"` 63 | CreatedAt string `yaml:"createdAt"` 64 | } 65 | 66 | type SidekickAppDatabaseBackupConfig struct { 67 | Target string `yaml:"target"` 68 | BucketName string `yaml:"bucketName"` 69 | BucketPath string `yaml:"path"` 70 | BucketRegion string `yaml:"region"` 71 | S3Endpoint string `yaml:"s3Endpoint"` 72 | } 73 | 74 | type SidekickAppDatabaseConfig struct { 75 | Type string `yaml:"type"` 76 | DbName string `yaml:"databaseName"` 77 | Backup SidekickAppDatabaseBackupConfig `yaml:"backup,omitempty"` 78 | } 79 | 80 | type SidekickAppConfig struct { 81 | Name string `yaml:"name"` 82 | Version string `yaml:"version"` 83 | Image string `yaml:"image"` 84 | Url string `yaml:"url"` 85 | Port uint64 `yaml:"port"` 86 | CreatedAt string `yaml:"createdAt"` 87 | Env SidekickAppEnvConfig `yaml:"env,omitempty"` 88 | DatabaseConfig SidekickAppDatabaseConfig `yaml:"database,omitempty"` 89 | PreviewEnvs map[string]SidekickPreview `yaml:"previewEnvs,omitempty"` 90 | } 91 | -------------------------------------------------------------------------------- /utils/utils.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright © 2024 Mahmoud Mousa 3 | 4 | Licensed under the GNU GPL License, Version 3.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | https://www.gnu.org/licenses/gpl-3.0.en.html 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | */ 15 | package utils 16 | 17 | import ( 18 | "bufio" 19 | "crypto/md5" 20 | "errors" 21 | "fmt" 22 | "os" 23 | "os/exec" 24 | "regexp" 25 | "strings" 26 | "time" 27 | 28 | "github.com/charmbracelet/log" 29 | "github.com/joho/godotenv" 30 | "github.com/pterm/pterm" 31 | "github.com/spf13/cobra" 32 | "github.com/spf13/viper" 33 | "golang.org/x/crypto/ssh" 34 | "gopkg.in/yaml.v3" 35 | ) 36 | 37 | type CommandsStage struct { 38 | Commands []string 39 | SpinnerSuccessMessage string 40 | SpinnerFailMessage string 41 | } 42 | 43 | func RunCommand(client *ssh.Client, cmd string) (chan string, chan string, error) { 44 | session, err := client.NewSession() 45 | errChannel := make(chan string) 46 | stdOutChannel := make(chan string) 47 | if err != nil { 48 | log.Fatalf("Failed to create session: %s", err) 49 | } 50 | defer session.Close() 51 | // Need to hook into the pipe of output coming from that session 52 | stdoutReader, err := session.StdoutPipe() 53 | if err != nil { 54 | return nil, nil, fmt.Errorf("error getting stdout reader: %s", err) 55 | } 56 | stderrReader, err := session.StderrPipe() 57 | if err != nil { 58 | return nil, nil, fmt.Errorf("error getting stderr reader: %s", err) 59 | } 60 | 61 | // make a scanner of that reader that will read as we get new stuff 62 | stdoutScanner := bufio.NewScanner(stdoutReader) 63 | stderrScanner := bufio.NewScanner(stderrReader) 64 | 65 | // start separate go routines to read from the pipes and print out 66 | go func() { 67 | for stdoutScanner.Scan() { 68 | stdOutChannel <- stdoutScanner.Text() 69 | // fmt.Printf("\033[34m[STDOUT]\033[0m %s\n", stdoutScanner.Text()) 70 | } 71 | }() 72 | 73 | go func() { 74 | for stderrScanner.Scan() { 75 | errChannel <- stderrScanner.Text() 76 | // fmt.Printf("\n\033[31m[STDERR]\033[0m %s\n", stderrScanner.Text()) 77 | } 78 | }() 79 | 80 | if err := session.Run(cmd); err != nil { 81 | defer session.Close() 82 | errString := <-errChannel 83 | return nil, nil, fmt.Errorf("error running command - %s: - %s", cmd, errString) 84 | } 85 | 86 | time.Sleep(time.Millisecond * 500) 87 | return stdOutChannel, errChannel, nil 88 | } 89 | 90 | func RunCommands(client *ssh.Client, commands []string) error { 91 | for _, cmd := range commands { 92 | _, _, err := RunCommand(client, cmd) 93 | if err != nil { 94 | return err 95 | } 96 | 97 | } 98 | return nil 99 | } 100 | 101 | func RunStage(client *ssh.Client, stage CommandsStage) error { 102 | if err := RunCommands(client, stage.Commands); err != nil { 103 | return err 104 | } 105 | return nil 106 | } 107 | 108 | func IsValidIPAddress(ip string) bool { 109 | const ipPattern = `\b(?:\d{1,3}\.){3}\d{1,3}\b` 110 | 111 | re := regexp.MustCompile(ipPattern) 112 | 113 | return re.MatchString(ip) 114 | 115 | } 116 | 117 | func FileExists(filename string) bool { 118 | _, err := os.Stat(filename) 119 | if err == nil { 120 | return true 121 | } 122 | if os.IsNotExist(err) { 123 | return false 124 | } 125 | return false 126 | } 127 | 128 | func ViperInit() error { 129 | home, err := os.UserHomeDir() 130 | cobra.CheckErr(err) 131 | 132 | configPath := fmt.Sprintf("%s/.config/sidekick", home) 133 | 134 | viper.AddConfigPath(configPath) 135 | viper.SetConfigType("yaml") 136 | viper.SetConfigName("default") 137 | err = viper.ReadInConfig() 138 | if err != nil { 139 | return err 140 | } 141 | return nil 142 | } 143 | 144 | func LoadAppConfig() (SidekickAppConfig, error) { 145 | if !FileExists("./sidekick.yml") { 146 | return SidekickAppConfig{}, errors.New("Sidekick app config not found. Please run sidekick launch first") 147 | } 148 | appConfigFile := SidekickAppConfig{} 149 | content, err := os.ReadFile("./sidekick.yml") 150 | if err != nil { 151 | pterm.Error.Println("Unable to process your project config") 152 | os.Exit(1) 153 | } 154 | if err := yaml.Unmarshal(content, &appConfigFile); err != nil { 155 | panic(err) 156 | } 157 | 158 | return appConfigFile, nil 159 | } 160 | 161 | func HandleEnvFile(envFileName string, dockerEnvProperty *[]string, envFileChecksum *string) error { 162 | envFile, envFileErr := os.Open(fmt.Sprintf("./%s", envFileName)) 163 | if envFileErr != nil { 164 | return envFileErr 165 | } 166 | envMap, envParseErr := godotenv.Parse(envFile) 167 | if envParseErr != nil { 168 | return envParseErr 169 | } 170 | 171 | for key := range envMap { 172 | if strings.HasPrefix(key, "_") { 173 | continue 174 | } 175 | *dockerEnvProperty = append(*dockerEnvProperty, fmt.Sprintf("%s=${%s}", key, key)) 176 | } 177 | // calculate and store the hash of env file to re-encrypt later on when changed 178 | envFileContent, _ := godotenv.Marshal(envMap) 179 | *envFileChecksum = fmt.Sprintf("%x", md5.Sum([]byte(envFileContent))) 180 | envCmd := exec.Command("sh", "-s", "-", viper.GetString("publicKey"), fmt.Sprintf("./%s", envFileName)) 181 | // encrypt and save/override encrypted.env 182 | envCmd.Stdin = strings.NewReader(EnvEncryptionScript) 183 | if envCmdErr := envCmd.Run(); envCmdErr != nil { 184 | return envCmdErr 185 | } 186 | return nil 187 | } 188 | 189 | func WriteEnvFile(filename string, env map[string]string) error { 190 | f, err := os.Open(filename) 191 | if err != nil { 192 | return fmt.Errorf("error openign file: %w", err) 193 | } 194 | defer f.Close() 195 | 196 | for key, value := range env { 197 | // Check if the value contains spaces or special characters 198 | // and quote it if needed. This is important for robustness. 199 | if strings.ContainsAny(value, " \t\n\r\"") { 200 | value = fmt.Sprintf("\"%s\"", strings.ReplaceAll(value, "\"", "\\\"")) // Escape inner quotes 201 | } 202 | if _, err := f.WriteString(fmt.Sprintf("%s=%s\n", key, value)); err != nil { 203 | return fmt.Errorf("error writing to file: %w", err) 204 | } 205 | } 206 | return nil 207 | } 208 | -------------------------------------------------------------------------------- /utils/utils_test.go: -------------------------------------------------------------------------------- 1 | package utils_test 2 | 3 | import ( 4 | "crypto/md5" 5 | "fmt" 6 | "os" 7 | "testing" 8 | 9 | "github.com/joho/godotenv" 10 | "github.com/mightymoud/sidekick/utils" 11 | "github.com/spf13/viper" 12 | "github.com/stretchr/testify/assert" 13 | ) 14 | 15 | func TestHandleEnvFile(t *testing.T) { 16 | envFileName := "test.env" 17 | dockerEnvProperty := []string{} 18 | var envFileChecksum string 19 | 20 | envContent := "KEY1=value1\nKEY2=value2" 21 | 22 | err := os.WriteFile(envFileName, []byte(envContent), 0644) 23 | assert.NoError(t, err) 24 | defer os.Remove(envFileName) 25 | defer os.Remove("encrypted.env") 26 | envFile, envFileErr := os.Open(fmt.Sprintf("./%s", envFileName)) 27 | assert.NoError(t, envFileErr) 28 | 29 | envMap, envParseErr := godotenv.Parse(envFile) 30 | assert.NoError(t, envParseErr) 31 | envFileContent, envMarshalErr := godotenv.Marshal(envMap) 32 | assert.NoError(t, envMarshalErr) 33 | 34 | viper.Set("publicKey", "age1lgjx644dkpj2nas84pfe4dsd96tph8yxhgf6zfh58kqw06qycavsz00rzm") 35 | 36 | err = utils.HandleEnvFile(envFileName, &dockerEnvProperty, &envFileChecksum) 37 | assert.NoError(t, err) 38 | 39 | assert.Contains(t, dockerEnvProperty, "KEY2=${KEY2}") 40 | assert.Contains(t, dockerEnvProperty, "KEY1=${KEY1}") 41 | 42 | expectedChecksum := fmt.Sprintf("%x", md5.Sum([]byte(envFileContent))) 43 | assert.Equal(t, expectedChecksum, envFileChecksum) 44 | } 45 | func TestLoadAppConfig(t *testing.T) { 46 | configContent := ` 47 | name: test 48 | version: V1 49 | image: "" 50 | url: MOCK_URL 51 | port: 3000 52 | createdAt: Mon Nov 11 21:42:50 KST 2024 53 | ` 54 | err := os.WriteFile("sidekick.yml", []byte(configContent), 0644) 55 | assert.NoError(t, err) 56 | defer os.Remove("sidekick.yml") 57 | 58 | appConfig, err := utils.LoadAppConfig() 59 | assert.NoError(t, err) 60 | 61 | assert.Equal(t, "test", appConfig.Name) 62 | assert.Equal(t, "V1", appConfig.Version) 63 | assert.Equal(t, "MOCK_URL", appConfig.Url) 64 | } 65 | 66 | func TestLoadAppConfig_FileNotFound(t *testing.T) { 67 | os.Remove("sidekick.yml") 68 | 69 | _, err := utils.LoadAppConfig() 70 | assert.Error(t, err) 71 | assert.Equal(t, "Sidekick app config not found. Please run sidekick launch first", err.Error()) 72 | } 73 | --------------------------------------------------------------------------------