powerful but friendly backup program that runs in your tray, powered by restic devins.page/restray
go restic system-tray
2

Configure Feed

Select the types of activity you want to include in your feed.

init

intergrav (Jun 28, 2026, 6:02 AM EDT) bb5a768f

+3372
+1
.envrc
··· 1 + use flake
+6
.gitignore
··· 1 + .direnv 2 + .DS_Store 3 + bin/ 4 + dist/ 5 + result 6 + Restray
.static/preview-linux.png

This is a binary file and will not be displayed.

.static/preview-macos.png

This is a binary file and will not be displayed.

.static/preview-windows.png

This is a binary file and will not be displayed.

+674
LICENSE
··· 1 + GNU GENERAL PUBLIC LICENSE 2 + Version 3, 29 June 2007 3 + 4 + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> 5 + Everyone is permitted to copy and distribute verbatim copies 6 + of this license document, but changing it is not allowed. 7 + 8 + Preamble 9 + 10 + The GNU General Public License is a free, copyleft license for 11 + software and other kinds of works. 12 + 13 + The licenses for most software and other practical works are designed 14 + to take away your freedom to share and change the works. By contrast, 15 + the GNU General Public License is intended to guarantee your freedom to 16 + share and change all versions of a program--to make sure it remains free 17 + software for all its users. We, the Free Software Foundation, use the 18 + GNU General Public License for most of our software; it applies also to 19 + any other work released this way by its authors. You can apply it to 20 + your programs, too. 21 + 22 + When we speak of free software, we are referring to freedom, not 23 + price. Our General Public Licenses are designed to make sure that you 24 + have the freedom to distribute copies of free software (and charge for 25 + them if you wish), that you receive source code or can get it if you 26 + want it, that you can change the software or use pieces of it in new 27 + free programs, and that you know you can do these things. 28 + 29 + To protect your rights, we need to prevent others from denying you 30 + these rights or asking you to surrender the rights. Therefore, you have 31 + certain responsibilities if you distribute copies of the software, or if 32 + you modify it: responsibilities to respect the freedom of others. 33 + 34 + For example, if you distribute copies of such a program, whether 35 + gratis or for a fee, you must pass on to the recipients the same 36 + freedoms that you received. You must make sure that they, too, receive 37 + or can get the source code. And you must show them these terms so they 38 + know their rights. 39 + 40 + Developers that use the GNU GPL protect your rights with two steps: 41 + (1) assert copyright on the software, and (2) offer you this License 42 + giving you legal permission to copy, distribute and/or modify it. 43 + 44 + For the developers' and authors' protection, the GPL clearly explains 45 + that there is no warranty for this free software. For both users' and 46 + authors' sake, the GPL requires that modified versions be marked as 47 + changed, so that their problems will not be attributed erroneously to 48 + authors of previous versions. 49 + 50 + Some devices are designed to deny users access to install or run 51 + modified versions of the software inside them, although the manufacturer 52 + can do so. This is fundamentally incompatible with the aim of 53 + protecting users' freedom to change the software. The systematic 54 + pattern of such abuse occurs in the area of products for individuals to 55 + use, which is precisely where it is most unacceptable. Therefore, we 56 + have designed this version of the GPL to prohibit the practice for those 57 + products. If such problems arise substantially in other domains, we 58 + stand ready to extend this provision to those domains in future versions 59 + of the GPL, as needed to protect the freedom of users. 60 + 61 + Finally, every program is threatened constantly by software patents. 62 + States should not allow patents to restrict development and use of 63 + software on general-purpose computers, but in those that do, we wish to 64 + avoid the special danger that patents applied to a free program could 65 + make it effectively proprietary. To prevent this, the GPL assures that 66 + patents cannot be used to render the program non-free. 67 + 68 + The precise terms and conditions for copying, distribution and 69 + modification follow. 70 + 71 + TERMS AND CONDITIONS 72 + 73 + 0. Definitions. 74 + 75 + "This License" refers to version 3 of the GNU General Public License. 76 + 77 + "Copyright" also means copyright-like laws that apply to other kinds of 78 + works, such as semiconductor masks. 79 + 80 + "The Program" refers to any copyrightable work licensed under this 81 + License. Each licensee is addressed as "you". "Licensees" and 82 + "recipients" may be individuals or organizations. 83 + 84 + To "modify" a work means to copy from or adapt all or part of the work 85 + in a fashion requiring copyright permission, other than the making of an 86 + exact copy. The resulting work is called a "modified version" of the 87 + earlier work or a work "based on" the earlier work. 88 + 89 + A "covered work" means either the unmodified Program or a work based 90 + on the Program. 91 + 92 + To "propagate" a work means to do anything with it that, without 93 + permission, would make you directly or secondarily liable for 94 + infringement under applicable copyright law, except executing it on a 95 + computer or modifying a private copy. Propagation includes copying, 96 + distribution (with or without modification), making available to the 97 + public, and in some countries other activities as well. 98 + 99 + To "convey" a work means any kind of propagation that enables other 100 + parties to make or receive copies. Mere interaction with a user through 101 + a computer network, with no transfer of a copy, is not conveying. 102 + 103 + An interactive user interface displays "Appropriate Legal Notices" 104 + to the extent that it includes a convenient and prominently visible 105 + feature that (1) displays an appropriate copyright notice, and (2) 106 + tells the user that there is no warranty for the work (except to the 107 + extent that warranties are provided), that licensees may convey the 108 + work under this License, and how to view a copy of this License. If 109 + the interface presents a list of user commands or options, such as a 110 + menu, a prominent item in the list meets this criterion. 111 + 112 + 1. Source Code. 113 + 114 + The "source code" for a work means the preferred form of the work 115 + for making modifications to it. "Object code" means any non-source 116 + form of a work. 117 + 118 + A "Standard Interface" means an interface that either is an official 119 + standard defined by a recognized standards body, or, in the case of 120 + interfaces specified for a particular programming language, one that 121 + is widely used among developers working in that language. 122 + 123 + The "System Libraries" of an executable work include anything, other 124 + than the work as a whole, that (a) is included in the normal form of 125 + packaging a Major Component, but which is not part of that Major 126 + Component, and (b) serves only to enable use of the work with that 127 + Major Component, or to implement a Standard Interface for which an 128 + implementation is available to the public in source code form. A 129 + "Major Component", in this context, means a major essential component 130 + (kernel, window system, and so on) of the specific operating system 131 + (if any) on which the executable work runs, or a compiler used to 132 + produce the work, or an object code interpreter used to run it. 133 + 134 + The "Corresponding Source" for a work in object code form means all 135 + the source code needed to generate, install, and (for an executable 136 + work) run the object code and to modify the work, including scripts to 137 + control those activities. However, it does not include the work's 138 + System Libraries, or general-purpose tools or generally available free 139 + programs which are used unmodified in performing those activities but 140 + which are not part of the work. For example, Corresponding Source 141 + includes interface definition files associated with source files for 142 + the work, and the source code for shared libraries and dynamically 143 + linked subprograms that the work is specifically designed to require, 144 + such as by intimate data communication or control flow between those 145 + subprograms and other parts of the work. 146 + 147 + The Corresponding Source need not include anything that users 148 + can regenerate automatically from other parts of the Corresponding 149 + Source. 150 + 151 + The Corresponding Source for a work in source code form is that 152 + same work. 153 + 154 + 2. Basic Permissions. 155 + 156 + All rights granted under this License are granted for the term of 157 + copyright on the Program, and are irrevocable provided the stated 158 + conditions are met. This License explicitly affirms your unlimited 159 + permission to run the unmodified Program. The output from running a 160 + covered work is covered by this License only if the output, given its 161 + content, constitutes a covered work. This License acknowledges your 162 + rights of fair use or other equivalent, as provided by copyright law. 163 + 164 + You may make, run and propagate covered works that you do not 165 + convey, without conditions so long as your license otherwise remains 166 + in force. You may convey covered works to others for the sole purpose 167 + of having them make modifications exclusively for you, or provide you 168 + with facilities for running those works, provided that you comply with 169 + the terms of this License in conveying all material for which you do 170 + not control copyright. Those thus making or running the covered works 171 + for you must do so exclusively on your behalf, under your direction 172 + and control, on terms that prohibit them from making any copies of 173 + your copyrighted material outside their relationship with you. 174 + 175 + Conveying under any other circumstances is permitted solely under 176 + the conditions stated below. Sublicensing is not allowed; section 10 177 + makes it unnecessary. 178 + 179 + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 + 181 + No covered work shall be deemed part of an effective technological 182 + measure under any applicable law fulfilling obligations under article 183 + 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 + similar laws prohibiting or restricting circumvention of such 185 + measures. 186 + 187 + When you convey a covered work, you waive any legal power to forbid 188 + circumvention of technological measures to the extent such circumvention 189 + is effected by exercising rights under this License with respect to 190 + the covered work, and you disclaim any intention to limit operation or 191 + modification of the work as a means of enforcing, against the work's 192 + users, your or third parties' legal rights to forbid circumvention of 193 + technological measures. 194 + 195 + 4. Conveying Verbatim Copies. 196 + 197 + You may convey verbatim copies of the Program's source code as you 198 + receive it, in any medium, provided that you conspicuously and 199 + appropriately publish on each copy an appropriate copyright notice; 200 + keep intact all notices stating that this License and any 201 + non-permissive terms added in accord with section 7 apply to the code; 202 + keep intact all notices of the absence of any warranty; and give all 203 + recipients a copy of this License along with the Program. 204 + 205 + You may charge any price or no price for each copy that you convey, 206 + and you may offer support or warranty protection for a fee. 207 + 208 + 5. Conveying Modified Source Versions. 209 + 210 + You may convey a work based on the Program, or the modifications to 211 + produce it from the Program, in the form of source code under the 212 + terms of section 4, provided that you also meet all of these conditions: 213 + 214 + a) The work must carry prominent notices stating that you modified 215 + it, and giving a relevant date. 216 + 217 + b) The work must carry prominent notices stating that it is 218 + released under this License and any conditions added under section 219 + 7. This requirement modifies the requirement in section 4 to 220 + "keep intact all notices". 221 + 222 + c) You must license the entire work, as a whole, under this 223 + License to anyone who comes into possession of a copy. This 224 + License will therefore apply, along with any applicable section 7 225 + additional terms, to the whole of the work, and all its parts, 226 + regardless of how they are packaged. This License gives no 227 + permission to license the work in any other way, but it does not 228 + invalidate such permission if you have separately received it. 229 + 230 + d) If the work has interactive user interfaces, each must display 231 + Appropriate Legal Notices; however, if the Program has interactive 232 + interfaces that do not display Appropriate Legal Notices, your 233 + work need not make them do so. 234 + 235 + A compilation of a covered work with other separate and independent 236 + works, which are not by their nature extensions of the covered work, 237 + and which are not combined with it such as to form a larger program, 238 + in or on a volume of a storage or distribution medium, is called an 239 + "aggregate" if the compilation and its resulting copyright are not 240 + used to limit the access or legal rights of the compilation's users 241 + beyond what the individual works permit. Inclusion of a covered work 242 + in an aggregate does not cause this License to apply to the other 243 + parts of the aggregate. 244 + 245 + 6. Conveying Non-Source Forms. 246 + 247 + You may convey a covered work in object code form under the terms 248 + of sections 4 and 5, provided that you also convey the 249 + machine-readable Corresponding Source under the terms of this License, 250 + in one of these ways: 251 + 252 + a) Convey the object code in, or embodied in, a physical product 253 + (including a physical distribution medium), accompanied by the 254 + Corresponding Source fixed on a durable physical medium 255 + customarily used for software interchange. 256 + 257 + b) Convey the object code in, or embodied in, a physical product 258 + (including a physical distribution medium), accompanied by a 259 + written offer, valid for at least three years and valid for as 260 + long as you offer spare parts or customer support for that product 261 + model, to give anyone who possesses the object code either (1) a 262 + copy of the Corresponding Source for all the software in the 263 + product that is covered by this License, on a durable physical 264 + medium customarily used for software interchange, for a price no 265 + more than your reasonable cost of physically performing this 266 + conveying of source, or (2) access to copy the 267 + Corresponding Source from a network server at no charge. 268 + 269 + c) Convey individual copies of the object code with a copy of the 270 + written offer to provide the Corresponding Source. This 271 + alternative is allowed only occasionally and noncommercially, and 272 + only if you received the object code with such an offer, in accord 273 + with subsection 6b. 274 + 275 + d) Convey the object code by offering access from a designated 276 + place (gratis or for a charge), and offer equivalent access to the 277 + Corresponding Source in the same way through the same place at no 278 + further charge. You need not require recipients to copy the 279 + Corresponding Source along with the object code. If the place to 280 + copy the object code is a network server, the Corresponding Source 281 + may be on a different server (operated by you or a third party) 282 + that supports equivalent copying facilities, provided you maintain 283 + clear directions next to the object code saying where to find the 284 + Corresponding Source. Regardless of what server hosts the 285 + Corresponding Source, you remain obligated to ensure that it is 286 + available for as long as needed to satisfy these requirements. 287 + 288 + e) Convey the object code using peer-to-peer transmission, provided 289 + you inform other peers where the object code and Corresponding 290 + Source of the work are being offered to the general public at no 291 + charge under subsection 6d. 292 + 293 + A separable portion of the object code, whose source code is excluded 294 + from the Corresponding Source as a System Library, need not be 295 + included in conveying the object code work. 296 + 297 + A "User Product" is either (1) a "consumer product", which means any 298 + tangible personal property which is normally used for personal, family, 299 + or household purposes, or (2) anything designed or sold for incorporation 300 + into a dwelling. In determining whether a product is a consumer product, 301 + doubtful cases shall be resolved in favor of coverage. For a particular 302 + product received by a particular user, "normally used" refers to a 303 + typical or common use of that class of product, regardless of the status 304 + of the particular user or of the way in which the particular user 305 + actually uses, or expects or is expected to use, the product. A product 306 + is a consumer product regardless of whether the product has substantial 307 + commercial, industrial or non-consumer uses, unless such uses represent 308 + the only significant mode of use of the product. 309 + 310 + "Installation Information" for a User Product means any methods, 311 + procedures, authorization keys, or other information required to install 312 + and execute modified versions of a covered work in that User Product from 313 + a modified version of its Corresponding Source. The information must 314 + suffice to ensure that the continued functioning of the modified object 315 + code is in no case prevented or interfered with solely because 316 + modification has been made. 317 + 318 + If you convey an object code work under this section in, or with, or 319 + specifically for use in, a User Product, and the conveying occurs as 320 + part of a transaction in which the right of possession and use of the 321 + User Product is transferred to the recipient in perpetuity or for a 322 + fixed term (regardless of how the transaction is characterized), the 323 + Corresponding Source conveyed under this section must be accompanied 324 + by the Installation Information. But this requirement does not apply 325 + if neither you nor any third party retains the ability to install 326 + modified object code on the User Product (for example, the work has 327 + been installed in ROM). 328 + 329 + The requirement to provide Installation Information does not include a 330 + requirement to continue to provide support service, warranty, or updates 331 + for a work that has been modified or installed by the recipient, or for 332 + the User Product in which it has been modified or installed. Access to a 333 + network may be denied when the modification itself materially and 334 + adversely affects the operation of the network or violates the rules and 335 + protocols for communication across the network. 336 + 337 + Corresponding Source conveyed, and Installation Information provided, 338 + in accord with this section must be in a format that is publicly 339 + documented (and with an implementation available to the public in 340 + source code form), and must require no special password or key for 341 + unpacking, reading or copying. 342 + 343 + 7. Additional Terms. 344 + 345 + "Additional permissions" are terms that supplement the terms of this 346 + License by making exceptions from one or more of its conditions. 347 + Additional permissions that are applicable to the entire Program shall 348 + be treated as though they were included in this License, to the extent 349 + that they are valid under applicable law. If additional permissions 350 + apply only to part of the Program, that part may be used separately 351 + under those permissions, but the entire Program remains governed by 352 + this License without regard to the additional permissions. 353 + 354 + When you convey a copy of a covered work, you may at your option 355 + remove any additional permissions from that copy, or from any part of 356 + it. (Additional permissions may be written to require their own 357 + removal in certain cases when you modify the work.) You may place 358 + additional permissions on material, added by you to a covered work, 359 + for which you have or can give appropriate copyright permission. 360 + 361 + Notwithstanding any other provision of this License, for material you 362 + add to a covered work, you may (if authorized by the copyright holders of 363 + that material) supplement the terms of this License with terms: 364 + 365 + a) Disclaiming warranty or limiting liability differently from the 366 + terms of sections 15 and 16 of this License; or 367 + 368 + b) Requiring preservation of specified reasonable legal notices or 369 + author attributions in that material or in the Appropriate Legal 370 + Notices displayed by works containing it; or 371 + 372 + c) Prohibiting misrepresentation of the origin of that material, or 373 + requiring that modified versions of such material be marked in 374 + reasonable ways as different from the original version; or 375 + 376 + d) Limiting the use for publicity purposes of names of licensors or 377 + authors of the material; or 378 + 379 + e) Declining to grant rights under trademark law for use of some 380 + trade names, trademarks, or service marks; or 381 + 382 + f) Requiring indemnification of licensors and authors of that 383 + material by anyone who conveys the material (or modified versions of 384 + it) with contractual assumptions of liability to the recipient, for 385 + any liability that these contractual assumptions directly impose on 386 + those licensors and authors. 387 + 388 + All other non-permissive additional terms are considered "further 389 + restrictions" within the meaning of section 10. If the Program as you 390 + received it, or any part of it, contains a notice stating that it is 391 + governed by this License along with a term that is a further 392 + restriction, you may remove that term. If a license document contains 393 + a further restriction but permits relicensing or conveying under this 394 + License, you may add to a covered work material governed by the terms 395 + of that license document, provided that the further restriction does 396 + not survive such relicensing or conveying. 397 + 398 + If you add terms to a covered work in accord with this section, you 399 + must place, in the relevant source files, a statement of the 400 + additional terms that apply to those files, or a notice indicating 401 + where to find the applicable terms. 402 + 403 + Additional terms, permissive or non-permissive, may be stated in the 404 + form of a separately written license, or stated as exceptions; 405 + the above requirements apply either way. 406 + 407 + 8. Termination. 408 + 409 + You may not propagate or modify a covered work except as expressly 410 + provided under this License. Any attempt otherwise to propagate or 411 + modify it is void, and will automatically terminate your rights under 412 + this License (including any patent licenses granted under the third 413 + paragraph of section 11). 414 + 415 + However, if you cease all violation of this License, then your 416 + license from a particular copyright holder is reinstated (a) 417 + provisionally, unless and until the copyright holder explicitly and 418 + finally terminates your license, and (b) permanently, if the copyright 419 + holder fails to notify you of the violation by some reasonable means 420 + prior to 60 days after the cessation. 421 + 422 + Moreover, your license from a particular copyright holder is 423 + reinstated permanently if the copyright holder notifies you of the 424 + violation by some reasonable means, this is the first time you have 425 + received notice of violation of this License (for any work) from that 426 + copyright holder, and you cure the violation prior to 30 days after 427 + your receipt of the notice. 428 + 429 + Termination of your rights under this section does not terminate the 430 + licenses of parties who have received copies or rights from you under 431 + this License. If your rights have been terminated and not permanently 432 + reinstated, you do not qualify to receive new licenses for the same 433 + material under section 10. 434 + 435 + 9. Acceptance Not Required for Having Copies. 436 + 437 + You are not required to accept this License in order to receive or 438 + run a copy of the Program. Ancillary propagation of a covered work 439 + occurring solely as a consequence of using peer-to-peer transmission 440 + to receive a copy likewise does not require acceptance. However, 441 + nothing other than this License grants you permission to propagate or 442 + modify any covered work. These actions infringe copyright if you do 443 + not accept this License. Therefore, by modifying or propagating a 444 + covered work, you indicate your acceptance of this License to do so. 445 + 446 + 10. Automatic Licensing of Downstream Recipients. 447 + 448 + Each time you convey a covered work, the recipient automatically 449 + receives a license from the original licensors, to run, modify and 450 + propagate that work, subject to this License. You are not responsible 451 + for enforcing compliance by third parties with this License. 452 + 453 + An "entity transaction" is a transaction transferring control of an 454 + organization, or substantially all assets of one, or subdividing an 455 + organization, or merging organizations. If propagation of a covered 456 + work results from an entity transaction, each party to that 457 + transaction who receives a copy of the work also receives whatever 458 + licenses to the work the party's predecessor in interest had or could 459 + give under the previous paragraph, plus a right to possession of the 460 + Corresponding Source of the work from the predecessor in interest, if 461 + the predecessor has it or can get it with reasonable efforts. 462 + 463 + You may not impose any further restrictions on the exercise of the 464 + rights granted or affirmed under this License. For example, you may 465 + not impose a license fee, royalty, or other charge for exercise of 466 + rights granted under this License, and you may not initiate litigation 467 + (including a cross-claim or counterclaim in a lawsuit) alleging that 468 + any patent claim is infringed by making, using, selling, offering for 469 + sale, or importing the Program or any portion of it. 470 + 471 + 11. Patents. 472 + 473 + A "contributor" is a copyright holder who authorizes use under this 474 + License of the Program or a work on which the Program is based. The 475 + work thus licensed is called the contributor's "contributor version". 476 + 477 + A contributor's "essential patent claims" are all patent claims 478 + owned or controlled by the contributor, whether already acquired or 479 + hereafter acquired, that would be infringed by some manner, permitted 480 + by this License, of making, using, or selling its contributor version, 481 + but do not include claims that would be infringed only as a 482 + consequence of further modification of the contributor version. For 483 + purposes of this definition, "control" includes the right to grant 484 + patent sublicenses in a manner consistent with the requirements of 485 + this License. 486 + 487 + Each contributor grants you a non-exclusive, worldwide, royalty-free 488 + patent license under the contributor's essential patent claims, to 489 + make, use, sell, offer for sale, import and otherwise run, modify and 490 + propagate the contents of its contributor version. 491 + 492 + In the following three paragraphs, a "patent license" is any express 493 + agreement or commitment, however denominated, not to enforce a patent 494 + (such as an express permission to practice a patent or covenant not to 495 + sue for patent infringement). To "grant" such a patent license to a 496 + party means to make such an agreement or commitment not to enforce a 497 + patent against the party. 498 + 499 + If you convey a covered work, knowingly relying on a patent license, 500 + and the Corresponding Source of the work is not available for anyone 501 + to copy, free of charge and under the terms of this License, through a 502 + publicly available network server or other readily accessible means, 503 + then you must either (1) cause the Corresponding Source to be so 504 + available, or (2) arrange to deprive yourself of the benefit of the 505 + patent license for this particular work, or (3) arrange, in a manner 506 + consistent with the requirements of this License, to extend the patent 507 + license to downstream recipients. "Knowingly relying" means you have 508 + actual knowledge that, but for the patent license, your conveying the 509 + covered work in a country, or your recipient's use of the covered work 510 + in a country, would infringe one or more identifiable patents in that 511 + country that you have reason to believe are valid. 512 + 513 + If, pursuant to or in connection with a single transaction or 514 + arrangement, you convey, or propagate by procuring conveyance of, a 515 + covered work, and grant a patent license to some of the parties 516 + receiving the covered work authorizing them to use, propagate, modify 517 + or convey a specific copy of the covered work, then the patent license 518 + you grant is automatically extended to all recipients of the covered 519 + work and works based on it. 520 + 521 + A patent license is "discriminatory" if it does not include within 522 + the scope of its coverage, prohibits the exercise of, or is 523 + conditioned on the non-exercise of one or more of the rights that are 524 + specifically granted under this License. You may not convey a covered 525 + work if you are a party to an arrangement with a third party that is 526 + in the business of distributing software, under which you make payment 527 + to the third party based on the extent of your activity of conveying 528 + the work, and under which the third party grants, to any of the 529 + parties who would receive the covered work from you, a discriminatory 530 + patent license (a) in connection with copies of the covered work 531 + conveyed by you (or copies made from those copies), or (b) primarily 532 + for and in connection with specific products or compilations that 533 + contain the covered work, unless you entered into that arrangement, 534 + or that patent license was granted, prior to 28 March 2007. 535 + 536 + Nothing in this License shall be construed as excluding or limiting 537 + any implied license or other defenses to infringement that may 538 + otherwise be available to you under applicable patent law. 539 + 540 + 12. No Surrender of Others' Freedom. 541 + 542 + If conditions are imposed on you (whether by court order, agreement or 543 + otherwise) that contradict the conditions of this License, they do not 544 + excuse you from the conditions of this License. If you cannot convey a 545 + covered work so as to satisfy simultaneously your obligations under this 546 + License and any other pertinent obligations, then as a consequence you may 547 + not convey it at all. For example, if you agree to terms that obligate you 548 + to collect a royalty for further conveying from those to whom you convey 549 + the Program, the only way you could satisfy both those terms and this 550 + License would be to refrain entirely from conveying the Program. 551 + 552 + 13. Use with the GNU Affero General Public License. 553 + 554 + Notwithstanding any other provision of this License, you have 555 + permission to link or combine any covered work with a work licensed 556 + under version 3 of the GNU Affero General Public License into a single 557 + combined work, and to convey the resulting work. The terms of this 558 + License will continue to apply to the part which is the covered work, 559 + but the special requirements of the GNU Affero General Public License, 560 + section 13, concerning interaction through a network will apply to the 561 + combination as such. 562 + 563 + 14. Revised Versions of this License. 564 + 565 + The Free Software Foundation may publish revised and/or new versions of 566 + the GNU General Public License from time to time. Such new versions will 567 + be similar in spirit to the present version, but may differ in detail to 568 + address new problems or concerns. 569 + 570 + Each version is given a distinguishing version number. If the 571 + Program specifies that a certain numbered version of the GNU General 572 + Public License "or any later version" applies to it, you have the 573 + option of following the terms and conditions either of that numbered 574 + version or of any later version published by the Free Software 575 + Foundation. If the Program does not specify a version number of the 576 + GNU General Public License, you may choose any version ever published 577 + by the Free Software Foundation. 578 + 579 + If the Program specifies that a proxy can decide which future 580 + versions of the GNU General Public License can be used, that proxy's 581 + public statement of acceptance of a version permanently authorizes you 582 + to choose that version for the Program. 583 + 584 + Later license versions may give you additional or different 585 + permissions. However, no additional obligations are imposed on any 586 + author or copyright holder as a result of your choosing to follow a 587 + later version. 588 + 589 + 15. Disclaimer of Warranty. 590 + 591 + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 + APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 + HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 + OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 + PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 + IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 + ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 + 600 + 16. Limitation of Liability. 601 + 602 + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 + WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 + THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 + GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 + USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 + DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 + PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 + EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 + SUCH DAMAGES. 611 + 612 + 17. Interpretation of Sections 15 and 16. 613 + 614 + If the disclaimer of warranty and limitation of liability provided 615 + above cannot be given local legal effect according to their terms, 616 + reviewing courts shall apply local law that most closely approximates 617 + an absolute waiver of all civil liability in connection with the 618 + Program, unless a warranty or assumption of liability accompanies a 619 + copy of the Program in return for a fee. 620 + 621 + END OF TERMS AND CONDITIONS 622 + 623 + How to Apply These Terms to Your New Programs 624 + 625 + If you develop a new program, and you want it to be of the greatest 626 + possible use to the public, the best way to achieve this is to make it 627 + free software which everyone can redistribute and change under these terms. 628 + 629 + To do so, attach the following notices to the program. It is safest 630 + to attach them to the start of each source file to most effectively 631 + state the exclusion of warranty; and each file should have at least 632 + the "copyright" line and a pointer to where the full notice is found. 633 + 634 + <one line to give the program's name and a brief idea of what it does.> 635 + Copyright (C) <year> <name of author> 636 + 637 + This program is free software: you can redistribute it and/or modify 638 + it under the terms of the GNU General Public License as published by 639 + the Free Software Foundation, either version 3 of the License, or 640 + (at your option) any later version. 641 + 642 + This program is distributed in the hope that it will be useful, 643 + but WITHOUT ANY WARRANTY; without even the implied warranty of 644 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 + GNU General Public License for more details. 646 + 647 + You should have received a copy of the GNU General Public License 648 + along with this program. If not, see <https://www.gnu.org/licenses/>. 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 + <program> Copyright (C) <year> <name of author> 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 + <https://www.gnu.org/licenses/>. 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 + <https://www.gnu.org/licenses/why-not-lgpl.html>.
+114
README.md
··· 1 + # restray 2 + 3 + A simple Go application that runs in the background/system tray, that can schedule and manage [restic](https://restic.net) backups and profiles easily. 4 + 5 + Intended for desktops. Runs on MacOS, Windows, and Linux. If you're on GNOME, you will need to install [this extension](https://extensions.gnome.org/extension/615/appindicator-support) to interact with and use the app since GNOME doesn't natively support the system tray. 6 + 7 + This is new and somewhat work-in-progress/beta software. You might possibly encounter a bug or two that I haven't fixed yet, and if so, please make an issue. I don't really intend on adding many new features, but I will fix bugs and refine the codebase more over time. 8 + 9 + (Icon subject to maybe change in the future) 10 + 11 + ![Preview of Restray on MacOS](.static/preview-macos.png) 12 + 13 + ![Preview of Restray on Linux](.static/preview-linux.png) 14 + 15 + ![Preview of Restray on Windows](.static/preview-windows.png) 16 + 17 + ## Features 18 + 19 + - Initialize a repository if one doesn't already exist 20 + - Run backups on a schedule with cron expressions, or just manually 21 + - Can detect battery power too and temporarily disable schedule 22 + - Multiple backup profiles with different schedules and different settings 23 + - Optional automatic pruning and checks after backups 24 + - Optional automatic retry and unlock for stale locks 25 + - Optional automatic `restic` binary download and updates 26 + - First tries to find `restic` in user's PATH, but if not found, user can manually click "download"/"update" restic and it'll manage it for them 27 + - This can also be automated daily by enabling "manage_restic" in config 28 + - Open a shell with your profile's environment and restic binary loaded, for restoring or other CLI operations without friction 29 + - Mount/browse repository snapshots on macOS/Linux 30 + - Requires [FUSE-T](https://www.fuse-t.org) or [macFUSE](https://macfuse.github.io) on macOS. Requires [FUSE](https://github.com/libfuse/libfuse) on Linux 31 + - I'd recommend something like [restic-browser](https://github.com/emuell/restic-browser) to browse on Windows, or just open the Shell and use the CLI 32 + - Full Disk Access detection and prompt on macOS 33 + - Config file hot-reloading 34 + 35 + ## Why 36 + 37 + I needed a replacement for Time Machine, since it's painfully slow, only exclusive to Macs, and only supports SMB now. I quite it's simplicity and ease-of-use though. Looking for other solutions, restic appeared to be a great fit, and I already use it for my server. 38 + 39 + However, I didn't find any option for scheduling restic backups that I actually liked. I did see [resticprofile](https://github.com/creativeprojects/resticprofile) which looks cool, and may be a better solution for some, check it out! But I'd still prefer a simple GUI and easier way to get started personally. 40 + 41 + So here's Restray which should hopefully solve that :) 42 + 43 + ## Building 44 + 45 + I'm not distributing Restray yet, but if you have [Nix](https://nixos.org)/NixOS/nix-darwin, just run `nix build` or add this repo to your flake and install the package. 46 + 47 + If you don't have Nix, install the dependencies from `flake.nix`'s devshell and use `just build` or `just package` to build/package for your current platform. You can also cross-compile to other platforms, for example `just build linux amd64`. 48 + 49 + ## Configuration 50 + 51 + ### `[general]` 52 + 53 + | Key | Type | Default | Description | 54 + | ------------------ | ------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | 55 + | `manage_restic` | bool | `false` | If restic is not found in PATH, automatically downloads and updates a self-managed restic binary daily from GitHub | 56 + | `notifications` | string | `"none"` | `"all"` (success + errors), `"errors"` (errors only), or `"none"` (silent) | 57 + | `schedule_display` | string | `"description"` | `"description"` (human-readable, e.g. "every 6 hours"), `"cron"` (raw expression, e.g. "0 \* \* \* \*"), or `"none"` | 58 + | `terminal` | string | `""` | Terminal emulator used in "Shell" and "View Log". If unset, MacOS will use `Terminal.app`. Linux will use default. Not used on Windows. e.g. "Ghostty" | 59 + 60 + ### `[[profile]]` 61 + 62 + You can create multiple of these sections for separate backup targets. Each profile has its own schedule, repository, environment, etc. 63 + 64 + | Key | Type | Default | Description | 65 + | ------------ | ------ | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | 66 + | `name` | string | `"default"` | Name for the profile | 67 + | `env_file` | string | `<config_dir>/<name>.env` | Path to the environment file with `RESTIC_REPOSITORY`, `RESTIC_PASSWORD`, etc. | 68 + | `retry_lock` | string | `"2m"` | How long to retry acquiring a repository lock (e.g. `"5m"`, `"30s"`). Will automatically attempt to clear stale locks after this timeout. Set to `"0"` to disable | 69 + 70 + #### `[profile.schedule]` 71 + 72 + | Key | Type | Default | Description | 73 + | ------------ | ------ | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | 74 + | `cron` | string | `""` | Set to an empty string to disable the schedule entirely. Cron expression for profile schedule (for help, see [crontab.guru](https://crontab.guru)) | 75 + | `on_battery` | bool | `false` | Whether to run schedule while on battery power | 76 + | `backup` | bool | `true` | Run backup on schedule | 77 + | `prune` | bool | `false` | Run prune on schedule | 78 + | `check` | bool | `false` | Run check on schedule | 79 + 80 + #### `[profile.backup]` 81 + 82 + | Key | Type | Default | Description | 83 + | ---------------- | -------- | -------------------------------------------- | ------------------------------------------------------------------------- | 84 + | `paths` | string[] | `[]` | Paths to back up, e.g. `["/Users/user/Documents", "/home/user/Projects"]` | 85 + | `args` | string[] | `["--exclude-caches", "--exclude", "*.tmp"]` | Extra arguments passed to `restic backup` | 86 + | `args_scheduled` | string[] | `["--tag", "scheduled"]` | Extra arguments appended (not replaced) when running from schedule | 87 + 88 + #### `[profile.prune]` 89 + 90 + | Key | Type | Default | Description | 91 + | ------ | -------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------- | 92 + | `args` | string[] | `["--keep-last", "4", "--keep-hourly", "24", "--keep-daily", "7", "--keep-weekly", "4", "--keep-monthly", "12"]` | Extra arguments passed to `restic forget --prune` | 93 + 94 + #### `[profile.check]` 95 + 96 + | Key | Type | Default | Description | 97 + | ------ | -------- | ------- | ----------------------------------------------------------------- | 98 + | `args` | string[] | `[]` | Extra arguments passed to `restic check` (e.g. `["--read-data"]`) | 99 + 100 + #### `[profile.mount]` 101 + 102 + | Key | Type | Default | Description | 103 + | ------ | -------- | ------- | ------------------------------------------------------------------- | 104 + | `args` | string[] | `[]` | Extra arguments passed to `restic mount` (e.g. `["--allow-other"]`) | 105 + 106 + ## Libraries used 107 + 108 + - [github.com/fyne.io/systray](https://github.com/fyne-io/systray) - cross-platform system tray handler 109 + - [github.com/BurntSushi/toml](https://github.com/BurntSushi/toml) - parse TOML 110 + - [github.com/distatus/battery](https://github.com/distatus/battery) - battery status for schedule 111 + - [github.com/fsnotify/fsnotify](https://github.com/fsnotify/fsnotify) - hot-reloading 112 + - [github.com/gen2brain/beeep](https://github.com/gen2brain/beeep) - cross-platform notification handler 113 + - [github.com/robfig/cron](https://github.com/robfig/cron) - cron scheduler 114 + - [github.com/lnquy/cron](https://github.com/lnquy/cron) - convert cron to human-readable expression
+447
config.go
··· 1 + package main 2 + 3 + import ( 4 + "bufio" 5 + _ "embed" 6 + "fmt" 7 + "log" 8 + "os" 9 + "os/exec" 10 + "path/filepath" 11 + "runtime" 12 + "strings" 13 + "time" 14 + 15 + "github.com/BurntSushi/toml" 16 + "github.com/fsnotify/fsnotify" 17 + ) 18 + 19 + //go:embed templates/config.toml 20 + var defaultConfigTemplate string 21 + 22 + //go:embed templates/default.env 23 + var defaultEnvTemplate string 24 + 25 + type Schedule struct { 26 + Cron string `toml:"cron"` 27 + OnBattery bool `toml:"on_battery"` 28 + Backup *bool `toml:"backup"` 29 + Prune bool `toml:"prune"` 30 + Check bool `toml:"check"` 31 + } 32 + 33 + func (s Schedule) BackupEnabled() bool { 34 + return s.Backup == nil || *s.Backup 35 + } 36 + 37 + type Backup struct { 38 + Paths []string `toml:"paths"` 39 + Args []string `toml:"args"` 40 + ArgsScheduled []string `toml:"args_scheduled"` 41 + } 42 + 43 + type Prune struct { 44 + Args []string `toml:"args"` 45 + } 46 + 47 + type Check struct { 48 + Args []string `toml:"args"` 49 + } 50 + 51 + type Mount struct { 52 + Args []string `toml:"args"` 53 + } 54 + 55 + type Profile struct { 56 + Name string `toml:"name"` 57 + EnvFile string `toml:"env_file"` 58 + RetryLock string `toml:"retry_lock"` 59 + Schedule Schedule `toml:"schedule"` 60 + Backup Backup `toml:"backup"` 61 + Prune Prune `toml:"prune"` 62 + Check Check `toml:"check"` 63 + Mount Mount `toml:"mount"` 64 + } 65 + 66 + type General struct { 67 + ManageRestic bool `toml:"manage_restic"` 68 + Notifications string `toml:"notifications"` 69 + ScheduleDisplay string `toml:"schedule_display"` 70 + Terminal string `toml:"terminal"` 71 + } 72 + 73 + type Config struct { 74 + General General `toml:"general"` 75 + Profile []Profile `toml:"profile"` 76 + } 77 + 78 + func parseEnvFile(path string) (map[string]string, error) { 79 + f, err := os.Open(path) 80 + if err != nil { 81 + return nil, err 82 + } 83 + defer f.Close() 84 + 85 + env := make(map[string]string) 86 + scanner := bufio.NewScanner(f) 87 + for scanner.Scan() { 88 + line := strings.TrimSpace(scanner.Text()) 89 + if line == "" || strings.HasPrefix(line, "#") { 90 + continue 91 + } 92 + line = strings.TrimPrefix(line, "export ") 93 + key, val, ok := strings.Cut(line, "=") 94 + if !ok { 95 + continue 96 + } 97 + key = strings.TrimSpace(key) 98 + val = strings.TrimSpace(val) 99 + if len(val) >= 2 && (val[0] == '"' || val[0] == '\'') && val[len(val)-1] == val[0] { 100 + val = val[1 : len(val)-1] 101 + } 102 + env[key] = val 103 + } 104 + return env, nil 105 + } 106 + 107 + func (prof Profile) configError() string { 108 + vars, err := parseEnvFile(prof.EnvFile) 109 + if err != nil { 110 + return "Env file not found" 111 + } 112 + if vars["RESTIC_REPOSITORY"] == "" { 113 + return "RESTIC_REPOSITORY not set in env file" 114 + } 115 + if vars["RESTIC_PASSWORD"] == "" && vars["RESTIC_PASSWORD_FILE"] == "" && vars["RESTIC_PASSWORD_COMMAND"] == "" { 116 + return "No password set in env file" 117 + } 118 + if len(prof.Backup.Paths) == 0 { 119 + return "No paths configured" 120 + } 121 + return "" 122 + } 123 + 124 + func (prof Profile) displayName() string { 125 + if prof.Name != "" { 126 + return prof.Name 127 + } 128 + if prof.EnvFile != "" { 129 + return strings.TrimSuffix(filepath.Base(prof.EnvFile), ".env") 130 + } 131 + return "Profile" 132 + } 133 + 134 + func needsFullDiskAccess() bool { 135 + if runtime.GOOS != "darwin" { 136 + return false 137 + } 138 + f, err := os.Open("/Library/Application Support/com.apple.TCC/TCC.db") // TODO: is this a good idea or should i be doing something else for FDA detection?? appears to work fine 139 + if err == nil { 140 + f.Close() 141 + } 142 + return os.IsPermission(err) 143 + } 144 + 145 + func openFullDiskAccessSettings() { 146 + exec.Command("open", "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles").Start() 147 + } 148 + 149 + func promptFullDiskAccess() { 150 + out, err := exec.Command("osascript", "-e", 151 + `display dialog "Restray needs Full Disk Access to be able to back up all your files." buttons {"Skip", "Open Settings"} default button "Open Settings" with title "Restray" with icon caution`).Output() 152 + if err == nil && strings.Contains(string(out), "Open Settings") { 153 + openFullDiskAccessSettings() 154 + } 155 + } 156 + 157 + func envFilesInsecure(profiles []Profile) bool { 158 + if runtime.GOOS == "windows" { 159 + return false 160 + } 161 + for _, p := range profiles { 162 + info, err := os.Stat(p.EnvFile) 163 + if err == nil && info.Mode().Perm()&0077 != 0 { 164 + return true 165 + } 166 + } 167 + return false 168 + } 169 + 170 + func fixEnvFilePermissions(profiles []Profile) { 171 + for _, p := range profiles { 172 + os.Chmod(p.EnvFile, 0600) 173 + } 174 + } 175 + 176 + func configDir() string { 177 + dir, _ := os.UserConfigDir() 178 + return filepath.Join(dir, "restray") 179 + } 180 + 181 + func configPath() string { return filepath.Join(configDir(), "config.toml") } 182 + func defaultEnvPath(name string) string { 183 + if name == "" { 184 + name = "default" 185 + } 186 + return filepath.Join(configDir(), name+".env") 187 + } 188 + func localResticPath() string { 189 + if runtime.GOOS == "windows" { 190 + return filepath.Join(configDir(), "restic.exe") 191 + } 192 + return filepath.Join(configDir(), "restic") 193 + } 194 + func logPath() string { return filepath.Join(configDir(), "restray.log") } 195 + func lockPath() string { return filepath.Join(configDir(), "restray.lock") } 196 + 197 + func loadConfig() Config { 198 + cfg := Config{} 199 + if _, err := toml.DecodeFile(configPath(), &cfg); err != nil && !os.IsNotExist(err) { 200 + log.Printf("config: %v", err) 201 + } 202 + if cfg.General.ScheduleDisplay == "" { 203 + cfg.General.ScheduleDisplay = "description" 204 + } 205 + if len(cfg.Profile) == 0 { 206 + cfg.Profile = append(cfg.Profile, Profile{Name: "default"}) 207 + } 208 + for i := range cfg.Profile { 209 + prof := &cfg.Profile[i] 210 + if prof.EnvFile == "" { 211 + prof.EnvFile = defaultEnvPath(prof.Name) 212 + } 213 + if prof.RetryLock == "" { 214 + prof.RetryLock = "2m" 215 + } 216 + if prof.Backup.Args == nil { 217 + prof.Backup.Args = []string{"--exclude-caches", "--exclude", "*.tmp"} 218 + } 219 + if prof.Backup.ArgsScheduled == nil { 220 + prof.Backup.ArgsScheduled = []string{"--tag", "scheduled"} 221 + } 222 + if prof.Prune.Args == nil { 223 + prof.Prune.Args = []string{ 224 + "--keep-last", "4", 225 + "--keep-hourly", "24", 226 + "--keep-daily", "7", 227 + "--keep-weekly", "4", 228 + "--keep-monthly", "12", 229 + } 230 + } 231 + } 232 + return cfg 233 + } 234 + 235 + func defaultConfigContents() string { 236 + return strings.ReplaceAll(defaultConfigTemplate, "{{ENV_FILE}}", filepath.ToSlash(defaultEnvPath("default"))) 237 + } 238 + 239 + func ensureConfigFile() { 240 + p := configPath() 241 + if _, err := os.Stat(p); err == nil { 242 + return 243 + } 244 + os.MkdirAll(filepath.Dir(p), 0700) 245 + os.WriteFile(p, []byte(defaultConfigContents()), 0600) 246 + } 247 + 248 + func ensureEnvFile(path string) { 249 + if _, err := os.Stat(path); err == nil { 250 + return 251 + } 252 + os.MkdirAll(filepath.Dir(path), 0700) 253 + os.WriteFile(path, []byte(defaultEnvTemplate), 0600) 254 + } 255 + 256 + func openFile(path string) { 257 + var cmd *exec.Cmd 258 + switch runtime.GOOS { 259 + case "darwin": 260 + cmd = exec.Command("open", path) 261 + case "windows": 262 + cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", path) 263 + default: 264 + cmd = exec.Command("xdg-open", path) 265 + } 266 + cmd.Start() 267 + } 268 + 269 + func openInEditor(path string) { 270 + if runtime.GOOS == "darwin" { 271 + exec.Command("open", "-t", path).Start() 272 + return 273 + } 274 + openFile(path) 275 + } 276 + 277 + func openConsole(prof Profile, profileCount int, terminal, tailFile string) { 278 + vars, err := parseEnvFile(prof.EnvFile) 279 + if err != nil { 280 + log.Printf("console: failed to read env file: %v", err) 281 + return 282 + } 283 + env := os.Environ() 284 + for k, v := range vars { 285 + env = append(env, k+"="+v) 286 + } 287 + if p := localResticPath(); fileExists(p) { 288 + dir := filepath.Dir(p) 289 + for i, e := range env { 290 + if strings.HasPrefix(e, "PATH=") { 291 + env[i] = "PATH=" + dir + string(os.PathListSeparator) + e[5:] 292 + break 293 + } 294 + } 295 + } 296 + 297 + consoleMsg := "Restray: environment loaded in shell. Run \"restic\" for commands." 298 + if profileCount > 1 { 299 + consoleMsg = fmt.Sprintf("Restray: environment for profile \"%s\" loaded in shell. Run \"restic\" for commands.", prof.displayName()) 300 + } 301 + tailMsg := "Restray: tailing log." 302 + 303 + var cmd *exec.Cmd 304 + switch runtime.GOOS { 305 + case "darwin": 306 + script, err := os.CreateTemp("", "restray-shell-*.sh") 307 + if err != nil { 308 + return 309 + } 310 + shell := os.Getenv("SHELL") 311 + if shell == "" { 312 + shell = "/bin/zsh" 313 + } 314 + fmt.Fprintf(script, "#!/bin/sh\n") 315 + for k, v := range vars { 316 + fmt.Fprintf(script, "export %s=%q\n", k, v) 317 + } 318 + if p := localResticPath(); fileExists(p) { 319 + fmt.Fprintf(script, "export PATH=%q:\"$PATH\"\n", filepath.Dir(p)) 320 + } 321 + fmt.Fprintf(script, "clear\n") 322 + fmt.Fprintf(script, "rm -f %q\n", script.Name()) 323 + fmt.Fprintf(script, "echo '%s'\n", consoleMsg) 324 + if tailFile != "" { 325 + fmt.Fprintf(script, "echo '%s'\n", tailMsg) 326 + fmt.Fprintf(script, "tail -n +1 -f %q &\n", tailFile) 327 + fmt.Fprintf(script, "TAIL_PID=$!\n") 328 + fmt.Fprintf(script, "trap 'kill $TAIL_PID 2>/dev/null; wait $TAIL_PID 2>/dev/null' INT\n") 329 + fmt.Fprintf(script, "wait $TAIL_PID\n") 330 + } 331 + fmt.Fprintf(script, "cd ~\n") 332 + fmt.Fprintf(script, "exec %s -l\n", shell) 333 + script.Close() 334 + os.Chmod(script.Name(), 0700) 335 + cmd = exec.Command("open", "-a", darwinTerminalApp(terminal), script.Name()) 336 + case "windows": 337 + script, err := os.CreateTemp("", "restray-shell-*.bat") 338 + if err != nil { 339 + return 340 + } 341 + fmt.Fprintf(script, "@echo off\r\n") 342 + for k, v := range vars { 343 + fmt.Fprintf(script, "set %s=%s\r\n", k, v) 344 + } 345 + if p := localResticPath(); fileExists(p) { 346 + fmt.Fprintf(script, "set PATH=%s;%%PATH%%\r\n", filepath.Dir(p)) 347 + } 348 + fmt.Fprintf(script, "echo %s\r\n", consoleMsg) 349 + if tailFile != "" { 350 + fmt.Fprintf(script, "echo %s\r\n", tailMsg) 351 + fmt.Fprintf(script, "echo.\r\n") 352 + fmt.Fprintf(script, "powershell -Command \"Get-Content -Path '%s' -Wait\"\r\n", tailFile) 353 + } 354 + fmt.Fprintf(script, "cmd /k\r\n") 355 + script.Close() 356 + cmd = exec.Command("cmd", "/c", "start", "", script.Name()) 357 + showConsole(cmd) 358 + default: 359 + shell := os.Getenv("SHELL") 360 + if shell == "" { 361 + shell = "/bin/sh" 362 + } 363 + term := terminal 364 + if term == "" { 365 + term = findTerminal() 366 + } 367 + if term == "" { 368 + log.Print("console: no terminal emulator found") 369 + return 370 + } 371 + var script string 372 + if tailFile != "" { 373 + script = fmt.Sprintf("clear; echo '%s'; echo '%s'; tail -n +1 -f %q; exec %s", consoleMsg, tailMsg, tailFile, shell) 374 + } else { 375 + script = fmt.Sprintf("clear; echo '%s'; exec %s", consoleMsg, shell) 376 + } 377 + cmd = exec.Command(term, "-e", shell, "-c", script) 378 + cmd.Env = env 379 + } 380 + cmd.Start() 381 + } 382 + 383 + func fileExists(path string) bool { 384 + _, err := os.Stat(path) 385 + return err == nil 386 + } 387 + 388 + func darwinTerminalApp(terminal string) string { 389 + t := strings.TrimSuffix(strings.ToLower(terminal), ".app") 390 + switch t { 391 + case "", "terminal": 392 + return "Terminal" 393 + case "iterm", "iterm2": 394 + return "iTerm" 395 + case "alacritty": 396 + return "Alacritty" 397 + case "kitty": 398 + return "kitty" 399 + case "ghostty": 400 + return "Ghostty" 401 + case "wezterm": 402 + return "WezTerm" 403 + default: 404 + return terminal 405 + } 406 + } 407 + 408 + func findTerminal() string { 409 + if t := os.Getenv("TERMINAL"); t != "" { 410 + return t 411 + } 412 + for _, t := range []string{"x-terminal-emulator", "gnome-terminal", "konsole", "xfce4-terminal", "xterm"} { 413 + if p, err := exec.LookPath(t); err == nil { 414 + return p 415 + } 416 + } 417 + return "" 418 + } 419 + 420 + func watchConfig(onChange func()) { 421 + watcher, err := fsnotify.NewWatcher() 422 + if err != nil { 423 + return 424 + } 425 + watcher.Add(configDir()) 426 + 427 + go func() { 428 + for range watcher.Errors { 429 + } 430 + }() 431 + go func() { 432 + var debounce *time.Timer 433 + for event := range watcher.Events { 434 + if event.Name == logPath() { 435 + continue 436 + } 437 + action := event.Has(fsnotify.Write) || event.Has(fsnotify.Create) || 438 + event.Has(fsnotify.Remove) || event.Has(fsnotify.Rename) 439 + if action { 440 + if debounce != nil { 441 + debounce.Stop() 442 + } 443 + debounce = time.AfterFunc(200*time.Millisecond, onChange) 444 + } 445 + } 446 + }() 447 + }
+46
exec_other.go
··· 1 + //go:build !windows 2 + 3 + package main 4 + 5 + import ( 6 + "io" 7 + "os" 8 + "os/exec" 9 + "runtime" 10 + "syscall" 11 + ) 12 + 13 + func hideWindow(_ *exec.Cmd) {} 14 + func showConsole(_ *exec.Cmd) {} 15 + 16 + func interruptProcess(p *os.Process) { 17 + p.Signal(os.Interrupt) 18 + } 19 + 20 + func lockFile(f *os.File) error { 21 + return syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) 22 + } 23 + 24 + func clearQuarantine(path string) { 25 + if runtime.GOOS != "darwin" { 26 + return 27 + } 28 + tmp := path + ".tmp" 29 + in, err := os.Open(path) 30 + if err != nil { 31 + return 32 + } 33 + out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY, 0755) 34 + if err != nil { 35 + in.Close() 36 + return 37 + } 38 + _, err = io.Copy(out, in) 39 + in.Close() 40 + out.Close() 41 + if err != nil { 42 + os.Remove(tmp) 43 + return 44 + } 45 + os.Rename(tmp, path) 46 + }
+40
exec_windows.go
··· 1 + package main 2 + 3 + import ( 4 + "os" 5 + "os/exec" 6 + "syscall" 7 + "unsafe" 8 + ) 9 + 10 + var modkernel32 = syscall.NewLazyDLL("kernel32.dll") 11 + var procLockFileEx = modkernel32.NewProc("LockFileEx") 12 + 13 + func hideWindow(cmd *exec.Cmd) { 14 + cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} 15 + } 16 + 17 + func showConsole(cmd *exec.Cmd) { 18 + cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 0x00000010} 19 + } 20 + 21 + func interruptProcess(p *os.Process) { 22 + p.Kill() 23 + } 24 + 25 + func clearQuarantine(_ string) {} 26 + 27 + func lockFile(f *os.File) error { 28 + var ol syscall.Overlapped 29 + r, _, err := procLockFileEx.Call( 30 + f.Fd(), 31 + 0x02|0x01, 32 + 0, 33 + 1, 0, 34 + uintptr(unsafe.Pointer(&ol)), 35 + ) 36 + if r == 0 { 37 + return err 38 + } 39 + return nil 40 + }
+61
flake.lock
··· 1 + { 2 + "nodes": { 3 + "flake-utils": { 4 + "inputs": { 5 + "systems": "systems" 6 + }, 7 + "locked": { 8 + "lastModified": 1731533236, 9 + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", 10 + "owner": "numtide", 11 + "repo": "flake-utils", 12 + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", 13 + "type": "github" 14 + }, 15 + "original": { 16 + "owner": "numtide", 17 + "repo": "flake-utils", 18 + "type": "github" 19 + } 20 + }, 21 + "nixpkgs": { 22 + "locked": { 23 + "lastModified": 1782175435, 24 + "narHash": "sha256-EMzXKmnOtBQ2MnvpiNOm7E+kOMvdPrIKaeg52Tip2Uk=", 25 + "owner": "NixOS", 26 + "repo": "nixpkgs", 27 + "rev": "89570f24e97e614aa34aa9ab1c927b6578a43775", 28 + "type": "github" 29 + }, 30 + "original": { 31 + "owner": "NixOS", 32 + "ref": "nixpkgs-unstable", 33 + "repo": "nixpkgs", 34 + "type": "github" 35 + } 36 + }, 37 + "root": { 38 + "inputs": { 39 + "flake-utils": "flake-utils", 40 + "nixpkgs": "nixpkgs" 41 + } 42 + }, 43 + "systems": { 44 + "locked": { 45 + "lastModified": 1681028828, 46 + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", 47 + "owner": "nix-systems", 48 + "repo": "default", 49 + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", 50 + "type": "github" 51 + }, 52 + "original": { 53 + "owner": "nix-systems", 54 + "repo": "default", 55 + "type": "github" 56 + } 57 + } 58 + }, 59 + "root": "root", 60 + "version": 7 61 + }
+78
flake.nix
··· 1 + { 2 + description = "System tray application to manage restic backups"; 3 + 4 + inputs = { 5 + nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; 6 + flake-utils.url = "github:numtide/flake-utils"; 7 + }; 8 + 9 + outputs = { 10 + self, 11 + nixpkgs, 12 + flake-utils, 13 + }: 14 + flake-utils.lib.eachDefaultSystem (system: let 15 + pkgs = nixpkgs.legacyPackages.${system}; 16 + isDarwin = pkgs.stdenv.hostPlatform.isDarwin; 17 + in { 18 + packages.default = pkgs.buildGoModule { 19 + pname = "restray"; 20 + version = "0.1.0"; 21 + src = ./.; 22 + vendorHash = "sha256-iYM2yvcTsYqn1pyB7jrqroYUfZM4ysWZnXKiLRVqkT0="; 23 + 24 + env = pkgs.lib.optionalAttrs isDarwin { 25 + CGO_CFLAGS = "-mmacosx-version-min=11.0"; 26 + CGO_LDFLAGS = "-mmacosx-version-min=11.0"; 27 + }; 28 + 29 + nativeBuildInputs = pkgs.lib.optionals (!isDarwin) [pkgs.pkg-config]; 30 + buildInputs = pkgs.lib.optionals (!isDarwin) [pkgs.glib]; 31 + 32 + postInstall = 33 + if isDarwin 34 + then '' 35 + mkdir -p $out/Applications/Restray.app/Contents/{MacOS,Resources} 36 + mv $out/bin/Restray $out/Applications/Restray.app/Contents/MacOS/Restray 37 + cp packaging/darwin/Info.plist $out/Applications/Restray.app/Contents/Info.plist 38 + cp packaging/darwin/restray.icns $out/Applications/Restray.app/Contents/Resources/restray.icns 39 + mkdir -p $out/bin 40 + ln -s $out/Applications/Restray.app/Contents/MacOS/Restray $out/bin/Restray 41 + '' 42 + else '' 43 + install -Dm644 packaging/linux/restray.desktop $out/share/applications/restray.desktop 44 + install -Dm644 packaging/linux/restray.png $out/share/icons/hicolor/256x256/apps/restray.png 45 + substituteInPlace $out/share/applications/restray.desktop \ 46 + --replace-fail "Exec=Restray" "Exec=$out/bin/Restray" 47 + ''; 48 + 49 + meta = { 50 + description = "Restic backup scheduler system tray app"; 51 + license = pkgs.lib.licenses.gpl3Only; 52 + platforms = pkgs.lib.platforms.linux ++ pkgs.lib.platforms.darwin; 53 + mainProgram = "Restray"; 54 + }; 55 + }; 56 + 57 + devShells.default = pkgs.mkShell { 58 + packages = with pkgs; 59 + [ 60 + go 61 + gotools # goimports 62 + go-tools # staticcheck 63 + 64 + gcc 65 + zig 66 + 67 + just 68 + nsis 69 + perl 70 + libicns 71 + imagemagick 72 + ] 73 + ++ lib.optionals (!isDarwin) [ 74 + pkg-config 75 + ]; 76 + }; 77 + }); 78 + }
+27
go.mod
··· 1 + module Restray 2 + 3 + go 1.26.3 4 + 5 + require ( 6 + fyne.io/systray v1.12.2 7 + github.com/BurntSushi/toml v1.6.0 8 + github.com/distatus/battery v0.11.0 9 + github.com/fsnotify/fsnotify v1.10.1 10 + github.com/gen2brain/beeep v0.11.2 11 + github.com/lnquy/cron v1.1.1 12 + github.com/robfig/cron/v3 v3.0.1 13 + ) 14 + 15 + require ( 16 + git.sr.ht/~jackmordaunt/go-toast v1.1.2 // indirect 17 + github.com/esiqveland/notify v0.14.0 // indirect 18 + github.com/go-ole/go-ole v1.3.0 // indirect 19 + github.com/godbus/dbus/v5 v5.2.2 // indirect 20 + github.com/jackmordaunt/icns/v3 v3.0.1 // indirect 21 + github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect 22 + github.com/sergeymakinen/go-bmp v1.0.0 // indirect 23 + github.com/sergeymakinen/go-ico v1.0.0 // indirect 24 + github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect 25 + golang.org/x/sys v0.46.0 // indirect 26 + howett.net/plist v1.0.1 // indirect 27 + )
+56
go.sum
··· 1 + fyne.io/systray v1.12.2 h1:Y8DZxgLHsVQt6rY9Zrkkg+j67S7vv/1F2viOWKPpVeA= 2 + fyne.io/systray v1.12.2/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs= 3 + git.sr.ht/~jackmordaunt/go-toast v1.1.2 h1:/yrfI55LRt1M7H1vkaw+NaH1+L1CDxrqDltwm5euVuE= 4 + git.sr.ht/~jackmordaunt/go-toast v1.1.2/go.mod h1:jA4OqHKTQ4AFBdwrSnwnskUIIS3HYzlJSgdzCKqfavo= 5 + github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= 6 + github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= 7 + github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 8 + github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 9 + github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 10 + github.com/distatus/battery v0.11.0 h1:KJk89gz90Iq/wJtbjjM9yUzBXV+ASV/EG2WOOL7N8lc= 11 + github.com/distatus/battery v0.11.0/go.mod h1:KmVkE8A8hpIX4T78QRdMktYpEp35QfOL8A8dwZBxq2k= 12 + github.com/esiqveland/notify v0.14.0 h1:LgIT/vYnziiw3d4ykaeyytc7jBUhD+Nvv3U7GIuPFj4= 13 + github.com/esiqveland/notify v0.14.0/go.mod h1:hesw/IRYTO0x99u1JPweAl4+5mwXJibQVUcP0Iu5ORE= 14 + github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= 15 + github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= 16 + github.com/gen2brain/beeep v0.11.2 h1:+KfiKQBbQCuhfJFPANZuJ+oxsSKAYNe88hIpJuyKWDA= 17 + github.com/gen2brain/beeep v0.11.2/go.mod h1:jQVvuwnLuwOcdctHn/uyh8horSBNJ8uGb9Cn2W4tvoc= 18 + github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= 19 + github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= 20 + github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= 21 + github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= 22 + github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= 23 + github.com/jackmordaunt/icns/v3 v3.0.1 h1:xxot6aNuGrU+lNgxz5I5H0qSeCjNKp8uTXB1j8D4S3o= 24 + github.com/jackmordaunt/icns/v3 v3.0.1/go.mod h1:5sHL59nqTd2ynTnowxB/MDQFhKNqkK8X687uKNygaSQ= 25 + github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= 26 + github.com/lnquy/cron v1.1.1 h1:iaDX1ublgQ9LBhA8l9BVU+FrTE1PPSPAuvAdhgdnXgA= 27 + github.com/lnquy/cron v1.1.1/go.mod h1:hu2Y7H68/8oKk6T4+K4qdbopbnaP4rGltK3ylWiiDss= 28 + github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= 29 + github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= 30 + github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 31 + github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 32 + github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= 33 + github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= 34 + github.com/sergeymakinen/go-bmp v1.0.0 h1:SdGTzp9WvCV0A1V0mBeaS7kQAwNLdVJbmHlqNWq0R+M= 35 + github.com/sergeymakinen/go-bmp v1.0.0/go.mod h1:/mxlAQZRLxSvJFNIEGGLBE/m40f3ZnUifpgVDlcUIEY= 36 + github.com/sergeymakinen/go-ico v1.0.0 h1:uL3khgvKkY6WfAetA+RqsguClBuu7HpvBB/nq/Jvr80= 37 + github.com/sergeymakinen/go-ico v1.0.0/go.mod h1:wQ47mTczswBO5F0NoDt7O0IXgnV4Xy3ojrroMQzyhUk= 38 + github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 39 + github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 40 + github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 41 + github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 42 + github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 43 + github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 44 + github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 45 + github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk= 46 + github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o= 47 + golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 48 + golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= 49 + golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= 50 + gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 51 + gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg= 52 + gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 53 + gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 54 + gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 55 + howett.net/plist v1.0.1 h1:37GdZ8tP09Q35o9ych3ehygcsL+HqKSwzctveSlarvM= 56 + howett.net/plist v1.0.1/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=
+97
icons.go
··· 1 + package main 2 + 3 + import ( 4 + "embed" 5 + "path" 6 + "runtime" 7 + "sort" 8 + "strings" 9 + "sync" 10 + "time" 11 + 12 + "fyne.io/systray" 13 + ) 14 + 15 + //go:embed icons/generated/* 16 + var iconFS embed.FS 17 + 18 + var ( 19 + animMu sync.Mutex 20 + animStop chan struct{} 21 + ) 22 + 23 + func cancelAnimation() { 24 + animMu.Lock() 25 + defer animMu.Unlock() 26 + if animStop != nil { 27 + close(animStop) 28 + animStop = nil 29 + } 30 + } 31 + 32 + func playAnimation(name string) { 33 + cancelAnimation() 34 + animMu.Lock() 35 + stop := make(chan struct{}) 36 + animStop = stop 37 + animMu.Unlock() 38 + 39 + frames := loadIcons(iconVariant() + "-" + name + "-") 40 + for _, frame := range frames { 41 + select { 42 + case <-stop: 43 + return 44 + default: 45 + setIcon(frame) 46 + time.Sleep(50 * time.Millisecond) 47 + } 48 + } 49 + } 50 + 51 + func loadIcons(prefix string) [][]byte { 52 + entries, _ := iconFS.ReadDir("icons/generated") 53 + var names []string 54 + for _, e := range entries { 55 + if strings.HasPrefix(e.Name(), prefix) { 56 + names = append(names, e.Name()) 57 + } 58 + } 59 + sort.Strings(names) 60 + frames := make([][]byte, len(names)) 61 + for i, n := range names { 62 + frames[i], _ = iconFS.ReadFile(path.Join("icons/generated", n)) 63 + } 64 + return frames 65 + } 66 + 67 + func setIcon(icon []byte) { 68 + if runtime.GOOS == "darwin" { 69 + systray.SetTemplateIcon(icon, icon) 70 + } else { 71 + systray.SetIcon(icon) 72 + } 73 + } 74 + 75 + func iconVariant() string { 76 + switch runtime.GOOS { 77 + case "darwin": 78 + return "macos" 79 + case "windows": 80 + return "windows" 81 + default: 82 + return "linux" 83 + } 84 + } 85 + 86 + func setIconAnimated(name string) { 87 + go playAnimation(name) 88 + } 89 + 90 + var alertIcon []byte 91 + 92 + func init() { 93 + frames := loadIcons(iconVariant() + "-fail-") 94 + if len(frames) > 0 { 95 + alertIcon = frames[len(frames)-1] 96 + } 97 + }
icons/busy.png

This is a binary file and will not be displayed.

icons/fail.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-00.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-01.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-02.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-03.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-04.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-05.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-06.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-07.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-08.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-09.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-10.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-11.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-12.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-13.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-14.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-15.png

This is a binary file and will not be displayed.

icons/generated/linux-busy-16.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-00.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-01.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-02.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-03.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-04.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-05.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-06.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-07.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-08.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-09.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-10.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-11.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-12.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-13.png

This is a binary file and will not be displayed.

icons/generated/linux-fail-14.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-00.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-01.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-02.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-03.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-04.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-05.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-06.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-07.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-08.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-09.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-10.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-11.png

This is a binary file and will not be displayed.

icons/generated/linux-idle-12.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-00.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-01.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-02.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-03.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-04.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-05.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-06.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-07.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-08.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-09.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-10.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-11.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-12.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-13.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-14.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-15.png

This is a binary file and will not be displayed.

icons/generated/macos-busy-16.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-00.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-01.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-02.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-03.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-04.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-05.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-06.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-07.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-08.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-09.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-10.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-11.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-12.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-13.png

This is a binary file and will not be displayed.

icons/generated/macos-fail-14.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-00.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-01.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-02.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-03.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-04.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-05.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-06.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-07.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-08.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-09.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-10.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-11.png

This is a binary file and will not be displayed.

icons/generated/macos-idle-12.png

This is a binary file and will not be displayed.

icons/generated/windows-busy-00.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-01.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-02.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-03.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-04.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-05.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-06.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-07.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-08.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-09.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-10.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-11.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-12.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-13.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-14.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-15.ico

This is a binary file and will not be displayed.

icons/generated/windows-busy-16.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-00.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-01.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-02.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-03.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-04.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-05.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-06.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-07.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-08.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-09.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-10.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-11.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-12.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-13.ico

This is a binary file and will not be displayed.

icons/generated/windows-fail-14.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-00.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-01.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-02.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-03.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-04.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-05.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-06.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-07.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-08.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-09.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-10.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-11.ico

This is a binary file and will not be displayed.

icons/generated/windows-idle-12.ico

This is a binary file and will not be displayed.

icons/idle.png

This is a binary file and will not be displayed.

+147
justfile
··· 1 + app := "Restray" 2 + version := "0.1.0" 3 + bin := "bin" 4 + dist := "dist" 5 + 6 + icons: 7 + #!/usr/bin/env bash 8 + set -e 9 + out="icons/generated" 10 + rm -rf "$out" 11 + mkdir -p "$out" 12 + for sheet in idle busy fail; do 13 + src="icons/$sheet.png" 14 + [ -f "$src" ] || continue 15 + dims=$(magick identify -format "%w %h" "$src") 16 + w=${dims% *} 17 + sz=${dims#* } 18 + cols=$((w / sz)) 19 + for ((i=0; i<cols; i++)); do 20 + x=$((i * sz)) 21 + n=$(printf "%02d" "$i") 22 + magick "$src" -crop "${sz}x${sz}+${x}+0" +repage /tmp/restray-frame.png 23 + cp /tmp/restray-frame.png "$out/linux-${sheet}-${n}.png" 24 + magick /tmp/restray-frame.png -alpha extract -background black -alpha shape "$out/macos-${sheet}-${n}.png" 25 + magick /tmp/restray-frame.png -define icon:auto-resize=64,48,32,16 "$out/windows-${sheet}-${n}.ico" 26 + done 27 + done 28 + rm -f /tmp/restray-frame.png 29 + # Last idle frame = app icon for packaging 30 + last=$(find "$out" -name "linux-idle-*.png" 2>/dev/null | sort | tail -1) 31 + if [ -n "$last" ]; then 32 + cp "$last" packaging/linux/restray.png 33 + magick "$last" -define icon:auto-resize=256,128,64,48,32,16 packaging/windows/restray.ico 34 + go run github.com/tc-hib/go-winres@latest simply --icon packaging/windows/restray.ico --out restray 35 + sizes="" 36 + for size in 16 32 128 256 512; do 37 + magick "$last" -resize ${size}x${size} "/tmp/restray-${size}.png" 38 + sizes="$sizes /tmp/restray-${size}.png" 39 + done 40 + png2icns packaging/darwin/restray.icns $sizes 41 + rm -f $sizes 42 + fi 43 + 44 + build target="" arch="": 45 + #!/usr/bin/env bash 46 + zig_arch() { 47 + case "$1" in 48 + amd64) echo "x86_64" ;; 49 + arm64) echo "aarch64" ;; 50 + *) echo "$1" ;; 51 + esac 52 + } 53 + build_one() { 54 + local os=$1 arch=$2 za 55 + za=$(zig_arch "$arch") 56 + case "$os" in 57 + darwin) 58 + export CGO_CFLAGS="-mmacosx-version-min=11.0" 59 + export CGO_LDFLAGS="-mmacosx-version-min=11.0" 60 + GOOS=darwin GOARCH=$arch go build -o {{bin}}/{{app}}-darwin-$arch . ;; 61 + linux) 62 + CGO_ENABLED=1 CC="zig cc -target ${za}-linux-gnu" \ 63 + GOOS=linux GOARCH=$arch go build -o {{bin}}/{{app}}-linux-$arch . ;; 64 + windows) 65 + CGO_ENABLED=1 CC="zig cc -target ${za}-windows-gnu" \ 66 + GOOS=windows GOARCH=$arch go build -ldflags -H=windowsgui -o {{bin}}/{{app}}-windows-$arch.exe . ;; 67 + esac 68 + } 69 + build_os() { 70 + local os=$1 71 + if [ -n "{{arch}}" ]; then build_one "$os" "{{arch}}" 72 + else build_one "$os" amd64 && build_one "$os" arm64; fi 73 + } 74 + case "{{target}}" in 75 + darwin|linux|windows) build_os "{{target}}" ;; 76 + all) build_os darwin && build_os linux && build_os windows ;; 77 + "") build_one "$(go env GOOS)" "$(go env GOARCH)" ;; 78 + *) echo "Unknown target: {{target}}. Use: darwin, linux, windows, all" && exit 1 ;; 79 + esac 80 + 81 + package target="" arch="": 82 + #!/usr/bin/env bash 83 + package_one() { 84 + local os=$1 arch=$2 85 + just build "$os" "$arch" && just "_package-$os" "$arch" 86 + } 87 + package_os() { 88 + local os=$1 89 + if [ -n "{{arch}}" ]; then package_one "$os" "{{arch}}" 90 + else package_one "$os" amd64 && package_one "$os" arm64; fi 91 + } 92 + case "{{target}}" in 93 + darwin|linux|windows) package_os "{{target}}" ;; 94 + all) package_os darwin && package_os windows && package_os linux ;; 95 + "") 96 + case "$(uname)" in 97 + Darwin) package_os darwin ;; 98 + MINGW*|MSYS*) package_os windows ;; 99 + *) package_os linux ;; 100 + esac ;; 101 + *) echo "Unknown target: {{target}}. Use: darwin, windows, linux, all" && exit 1 ;; 102 + esac 103 + 104 + _package-darwin arch: 105 + rm -rf {{dist}}/{{app}}.app 106 + mkdir -p {{dist}}/{{app}}.app/Contents/MacOS {{dist}}/{{app}}.app/Contents/Resources 107 + cp {{bin}}/{{app}}-darwin-{{arch}} {{dist}}/{{app}}.app/Contents/MacOS/{{app}} 108 + cp packaging/darwin/Info.plist {{dist}}/{{app}}.app/Contents/Info.plist 109 + cp packaging/darwin/restray.icns {{dist}}/{{app}}.app/Contents/Resources/restray.icns 110 + cd {{dist}} && zip -r {{app}}-{{version}}-darwin-{{arch}}.zip {{app}}.app 111 + rm -rf {{dist}}/{{app}}.app 112 + 113 + _package-windows arch: 114 + mkdir -p {{dist}} 115 + cp {{bin}}/{{app}}-windows-{{arch}}.exe {{bin}}/{{app}}.exe 116 + makensis -DARCH={{arch}} packaging/windows/installer.nsi 117 + rm {{bin}}/{{app}}.exe 118 + 119 + _package-linux arch: 120 + mkdir -p {{dist}} 121 + OUTPUT={{dist}}/{{app}}-{{version}}-linux-{{arch}}.AppImage linuxdeploy \ 122 + --executable={{bin}}/{{app}}-linux-{{arch}} \ 123 + --desktop-file=packaging/linux/restray.desktop \ 124 + --icon-file=packaging/linux/restray.png \ 125 + --output=appimage 126 + 127 + run: 128 + just build && {{bin}}/{{app}}-$(go env GOOS)-$(go env GOARCH) 129 + 130 + lint: 131 + goimports -w . 132 + go vet . 133 + staticcheck . 134 + 135 + bump new: 136 + #!/usr/bin/env bash 137 + set -euo pipefail 138 + [[ "{{new}}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "Usage: just bump X.Y.Z"; exit 1; } 139 + perl -pi -e 's/^version := ".*"/version := "{{new}}"/' justfile 140 + perl -pi -e 's/version = ".*"/version = "{{new}}"/' flake.nix 141 + perl -pi -e 's/!define VERSION ".*"/!define VERSION "{{new}}"/' packaging/windows/installer.nsi 142 + perl -pi -e 's|(<string>)[^<]*(</string>)|${1}{{new}}${2}| if $prev =~ /CFBundle(Version|ShortVersionString)/; $prev = $_' packaging/darwin/Info.plist 143 + echo "Bumped to {{new}}" 144 + grep -n "{{new}}" justfile flake.nix packaging/windows/installer.nsi packaging/darwin/Info.plist 145 + 146 + clean: 147 + rm -rf {{bin}} {{dist}} result
+26
main.go
··· 1 + package main 2 + 3 + import ( 4 + "log" 5 + "os" 6 + 7 + "fyne.io/systray" 8 + ) 9 + 10 + func main() { 11 + os.MkdirAll(configDir(), 0700) 12 + 13 + lock, err := os.OpenFile(lockPath(), os.O_CREATE|os.O_RDWR, 0600) 14 + if err != nil || lockFile(lock) != nil { 15 + return 16 + } 17 + defer lock.Close() 18 + 19 + f, err := os.OpenFile(logPath(), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600) 20 + if err == nil { 21 + log.SetOutput(f) 22 + log.SetFlags(log.Ldate | log.Ltime) 23 + } 24 + 25 + systray.Run(onReady, func() {}) 26 + }
+28
packaging/darwin/Info.plist
··· 1 + <?xml version="1.0" encoding="UTF-8"?> 2 + <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 3 + <plist version="1.0"> 4 + <dict> 5 + <key>CFBundleName</key> 6 + <string>Restray</string> 7 + <key>CFBundleExecutable</key> 8 + <string>Restray</string> 9 + <key>CFBundleIdentifier</key> 10 + <string>page.devins.restray</string> 11 + <key>CFBundleVersion</key> 12 + <string>0.1.0</string> 13 + <key>CFBundleShortVersionString</key> 14 + <string>0.1.0</string> 15 + <key>CFBundlePackageType</key> 16 + <string>APPL</string> 17 + <key>CFBundleInfoDictionaryVersion</key> 18 + <string>6.0</string> 19 + <key>CFBundleIconFile</key> 20 + <string>restray</string> 21 + <key>NSHighResolutionCapable</key> 22 + <true/> 23 + <key>LSMinimumSystemVersion</key> 24 + <string>11.0</string> 25 + <key>LSUIElement</key> 26 + <true/> 27 + </dict> 28 + </plist>
packaging/darwin/restray.icns

This is a binary file and will not be displayed.

+7
packaging/linux/restray.desktop
··· 1 + [Desktop Entry] 2 + Type=Application 3 + Name=Restray 4 + Comment=Restic Backup Scheduler 5 + Exec=Restray 6 + Icon=restray 7 + Categories=Utility;Archiving;
packaging/linux/restray.png

This is a binary file and will not be displayed.

+45
packaging/windows/installer.nsi
··· 1 + !include "MUI2.nsh" 2 + 3 + !define VERSION "0.1.0" 4 + 5 + Name "Restray" 6 + OutFile "..\..\dist\Restray-${VERSION}-windows-${ARCH}-setup.exe" 7 + InstallDir "$LOCALAPPDATA\Restray" 8 + RequestExecutionLevel user 9 + 10 + VIProductVersion "${VERSION}.0" 11 + VIAddVersionKey "ProductName" "Restray" 12 + VIAddVersionKey "ProductVersion" "${VERSION}" 13 + VIAddVersionKey "FileVersion" "${VERSION}" 14 + VIAddVersionKey "FileDescription" "Restray Installer" 15 + VIAddVersionKey "LegalCopyright" "Copyright © 2026 devins.page" 16 + 17 + !define MUI_ICON "restray.ico" 18 + !define MUI_UNICON "restray.ico" 19 + 20 + !insertmacro MUI_PAGE_DIRECTORY 21 + !insertmacro MUI_PAGE_INSTFILES 22 + !insertmacro MUI_LANGUAGE "English" 23 + 24 + Section "Install" 25 + SetOutPath "$INSTDIR" 26 + File "..\..\bin\Restray.exe" 27 + 28 + CreateDirectory "$SMPROGRAMS\Restray" 29 + CreateShortcut "$SMPROGRAMS\Restray\Restray.lnk" "$INSTDIR\Restray.exe" 30 + CreateShortcut "$SMSTARTUP\Restray.lnk" "$INSTDIR\Restray.exe" 31 + 32 + WriteUninstaller "$INSTDIR\Uninstall.exe" 33 + CreateShortcut "$SMPROGRAMS\Restray\Uninstall.lnk" "$INSTDIR\Uninstall.exe" 34 + SectionEnd 35 + 36 + Section "Uninstall" 37 + Delete "$INSTDIR\Restray.exe" 38 + Delete "$INSTDIR\Uninstall.exe" 39 + RMDir "$INSTDIR" 40 + 41 + Delete "$SMPROGRAMS\Restray\Restray.lnk" 42 + Delete "$SMPROGRAMS\Restray\Uninstall.lnk" 43 + RMDir "$SMPROGRAMS\Restray" 44 + Delete "$SMSTARTUP\Restray.lnk" 45 + SectionEnd
packaging/windows/restray.ico

This is a binary file and will not be displayed.

+748
restic.go
··· 1 + package main 2 + 3 + import ( 4 + "archive/zip" 5 + "bufio" 6 + "compress/bzip2" 7 + "context" 8 + "encoding/json" 9 + "fmt" 10 + "io" 11 + "log" 12 + "net/http" 13 + "os" 14 + "os/exec" 15 + "path/filepath" 16 + "runtime" 17 + "strings" 18 + "sync" 19 + "time" 20 + 21 + "fyne.io/systray" 22 + "github.com/gen2brain/beeep" 23 + ) 24 + 25 + var ( 26 + resticOnce sync.Once 27 + resticPath string 28 + resticManaged bool 29 + ) 30 + 31 + func findRestic() (path string, managed bool) { 32 + resticOnce.Do(func() { 33 + if p, err := exec.LookPath("restic"); err == nil { 34 + resticPath = p 35 + return 36 + } 37 + if p := findResticFromShell(); p != "" { 38 + resticPath = p 39 + return 40 + } 41 + p := localResticPath() 42 + if _, err := os.Stat(p); err == nil { 43 + resticPath = p 44 + resticManaged = true 45 + } 46 + }) 47 + return resticPath, resticManaged 48 + } 49 + 50 + func resetResticPath() { 51 + resticOnce = sync.Once{} 52 + resticPath = "" 53 + resticManaged = false 54 + } 55 + 56 + func findResticFromShell() string { 57 + if runtime.GOOS == "windows" { 58 + return "" 59 + } 60 + shell := os.Getenv("SHELL") 61 + if shell == "" { 62 + if runtime.GOOS == "darwin" { 63 + shell = "/bin/zsh" 64 + } else { 65 + shell = "/bin/sh" 66 + } 67 + } 68 + out, err := exec.Command(shell, "-l", "-c", "which restic").Output() 69 + if err == nil { 70 + if p := strings.TrimSpace(string(out)); p != "" { 71 + if _, err := os.Stat(p); err == nil { 72 + return p 73 + } 74 + } 75 + } 76 + for _, dir := range []string{ 77 + "/opt/homebrew/bin", 78 + "/usr/local/bin", 79 + filepath.Join(os.Getenv("HOME"), ".nix-profile/bin"), 80 + "/run/current-system/sw/bin", 81 + filepath.Join(os.Getenv("HOME"), ".local/bin"), 82 + } { 83 + p := filepath.Join(dir, "restic") 84 + if _, err := os.Stat(p); err == nil { 85 + return p 86 + } 87 + } 88 + return "" 89 + } 90 + 91 + func resticVersion(path string) string { 92 + cmd := exec.Command(path, "version") 93 + hideWindow(cmd) 94 + out, err := cmd.Output() 95 + if err != nil { 96 + return "" 97 + } 98 + parts := strings.Fields(string(out)) 99 + if len(parts) >= 2 { 100 + return parts[1] 101 + } 102 + return "" 103 + } 104 + 105 + func resticEnv(prof Profile) []string { 106 + env := os.Environ() 107 + vars, err := parseEnvFile(prof.EnvFile) 108 + if err != nil { 109 + return env 110 + } 111 + for k, v := range vars { 112 + env = append(env, k+"="+v) 113 + } 114 + return env 115 + } 116 + 117 + func resticCmd(prof Profile, args ...string) *exec.Cmd { 118 + path, _ := findRestic() 119 + log.Printf("[%s] run: restic %s", prof.displayName(), strings.Join(args, " ")) 120 + cmd := exec.Command(path, args...) 121 + cmd.Env = resticEnv(prof) 122 + hideWindow(cmd) 123 + return cmd 124 + } 125 + 126 + type repoResult struct { 127 + errMsg string 128 + needsInit bool 129 + } 130 + 131 + func repoStatus(prof Profile) repoResult { 132 + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) 133 + defer cancel() 134 + path, _ := findRestic() 135 + cmd := exec.CommandContext(ctx, path, "cat", "config", "--no-lock", "-q") 136 + cmd.Env = resticEnv(prof) 137 + hideWindow(cmd) 138 + out, err := cmd.CombinedOutput() 139 + if err != nil { 140 + if ctx.Err() != nil { 141 + return repoResult{errMsg: "Repository unreachable"} 142 + } 143 + lines := strings.Split(strings.TrimSpace(string(out)), "\n") 144 + msg, code := classifyError(err, lines[len(lines)-1]) 145 + return repoResult{errMsg: msg, needsInit: code == 10} 146 + } 147 + return repoResult{} 148 + } 149 + 150 + func latestResticVersion() (string, error) { 151 + client := &http.Client{ 152 + Timeout: 10 * time.Second, 153 + CheckRedirect: func(req *http.Request, via []*http.Request) error { 154 + return http.ErrUseLastResponse 155 + }, 156 + } 157 + resp, err := client.Get("https://github.com/restic/restic/releases/latest") 158 + if err != nil { 159 + return "", err 160 + } 161 + resp.Body.Close() 162 + loc := resp.Header.Get("Location") 163 + if loc == "" { 164 + return "", fmt.Errorf("no redirect from github") 165 + } 166 + parts := strings.Split(loc, "/") 167 + v := parts[len(parts)-1] 168 + if len(v) > 0 && v[0] == 'v' { 169 + v = v[1:] 170 + } 171 + return v, nil 172 + } 173 + 174 + func downloadRestic(mStatus prefixedMenuItem) error { 175 + mStatus.SetTitle("Fetching latest version...") 176 + version, err := latestResticVersion() 177 + if err != nil { 178 + log.Printf("failed to fetch latest version: %v", err) 179 + return err 180 + } 181 + if version == "" { 182 + log.Print("failed to determine latest version") 183 + return fmt.Errorf("failed to determine latest version") 184 + } 185 + 186 + ext := "bz2" 187 + if runtime.GOOS == "windows" { 188 + ext = "zip" 189 + } 190 + url := fmt.Sprintf("https://github.com/restic/restic/releases/download/v%s/restic_%s_%s_%s.%s", 191 + version, version, runtime.GOOS, runtime.GOARCH, ext) 192 + log.Printf("downloading restic %s", version) 193 + mStatus.SetTitle("Downloading restic " + version + "...") 194 + 195 + resp, err := http.Get(url) 196 + if err != nil { 197 + log.Printf("download failed: %v", err) 198 + return err 199 + } 200 + defer resp.Body.Close() 201 + if resp.StatusCode != 200 { 202 + log.Printf("download failed: %s", resp.Status) 203 + return fmt.Errorf("download failed: %s", resp.Status) 204 + } 205 + 206 + if runtime.GOOS == "windows" { 207 + err = extractResticZip(resp.Body) 208 + } else { 209 + err = extractResticBz2(resp.Body) 210 + } 211 + if err == nil { 212 + log.Printf("installed restic %s", version) 213 + resetResticPath() 214 + } 215 + return err 216 + } 217 + 218 + func extractResticBz2(r io.Reader) error { 219 + p := localResticPath() 220 + os.Remove(p) 221 + f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY, 0755) 222 + if err != nil { 223 + return err 224 + } 225 + if _, err := io.Copy(f, bzip2.NewReader(r)); err != nil { 226 + f.Close() 227 + return err 228 + } 229 + f.Close() 230 + clearQuarantine(p) 231 + return nil 232 + } 233 + 234 + func extractResticZip(r io.Reader) error { 235 + tmp, err := os.CreateTemp("", "restray-download-*.zip") 236 + if err != nil { 237 + return err 238 + } 239 + defer os.Remove(tmp.Name()) 240 + defer tmp.Close() 241 + 242 + if _, err := io.Copy(tmp, r); err != nil { 243 + return err 244 + } 245 + 246 + zr, err := zip.OpenReader(tmp.Name()) 247 + if err != nil { 248 + return err 249 + } 250 + defer zr.Close() 251 + 252 + for _, zf := range zr.File { 253 + if strings.HasSuffix(zf.Name, ".exe") { 254 + rc, err := zf.Open() 255 + if err != nil { 256 + return err 257 + } 258 + defer rc.Close() 259 + p := localResticPath() 260 + os.Remove(p) 261 + f, err := os.OpenFile(p, os.O_CREATE|os.O_WRONLY, 0755) 262 + if err != nil { 263 + return err 264 + } 265 + defer f.Close() 266 + if _, err = io.Copy(f, rc); err != nil { 267 + return err 268 + } 269 + clearQuarantine(p) 270 + return nil 271 + } 272 + } 273 + return fmt.Errorf("restic binary not found in zip") 274 + } 275 + 276 + func checkResticUpdate(resticPath string, autoUpdate bool, mUpdate *systray.MenuItem, mStatus prefixedMenuItem, onUpdated func()) { 277 + current := resticVersion(resticPath) 278 + latest, err := latestResticVersion() 279 + if err != nil || current == "" || latest == "" || current == latest { 280 + return 281 + } 282 + log.Printf("restic update available: %s → %s", current, latest) 283 + if autoUpdate { 284 + err = downloadRestic(mStatus) 285 + if err == nil { 286 + onUpdated() 287 + } 288 + return 289 + } 290 + mUpdate.SetTitle("Update Restic (" + current + " → " + latest + ")") 291 + mUpdate.Show() 292 + } 293 + 294 + type appState struct { 295 + mu sync.Mutex 296 + busyProfiles map[int]*exec.Cmd 297 + onBusyChanged func(bool) 298 + mountCmds map[int]*exec.Cmd 299 + mountStopping map[int]bool 300 + notifications string 301 + failStatus map[int]string 302 + } 303 + 304 + var state = appState{ 305 + busyProfiles: make(map[int]*exec.Cmd), 306 + mountCmds: make(map[int]*exec.Cmd), 307 + mountStopping: make(map[int]bool), 308 + failStatus: make(map[int]string), 309 + } 310 + 311 + func isProfileBusy(idx int) bool { 312 + state.mu.Lock() 313 + defer state.mu.Unlock() 314 + _, ok := state.busyProfiles[idx] 315 + return ok 316 + } 317 + 318 + func isAnyBusy() bool { 319 + state.mu.Lock() 320 + defer state.mu.Unlock() 321 + return len(state.busyProfiles) > 0 322 + } 323 + 324 + func setProfileBusy(idx int, active bool) { 325 + state.mu.Lock() 326 + wasBusy := len(state.busyProfiles) > 0 327 + if active { 328 + state.busyProfiles[idx] = nil 329 + } else { 330 + delete(state.busyProfiles, idx) 331 + } 332 + nowBusy := len(state.busyProfiles) > 0 333 + if nowBusy && !wasBusy { 334 + setIconAnimated("busy") 335 + } 336 + cb := state.onBusyChanged 337 + state.mu.Unlock() 338 + if cb != nil { 339 + cb(nowBusy) 340 + } 341 + } 342 + 343 + func setProfileBusyCmd(idx int, cmd *exec.Cmd) { 344 + state.mu.Lock() 345 + defer state.mu.Unlock() 346 + state.busyProfiles[idx] = cmd 347 + } 348 + 349 + func cancelProfile(idx int) { 350 + state.mu.Lock() 351 + defer state.mu.Unlock() 352 + if cmd := state.busyProfiles[idx]; cmd != nil && cmd.Process != nil { 353 + interruptProcess(cmd.Process) 354 + } 355 + } 356 + 357 + type stderrLogger struct { 358 + mu sync.Mutex 359 + last string 360 + } 361 + 362 + func (s *stderrLogger) lastLine() string { 363 + s.mu.Lock() 364 + defer s.mu.Unlock() 365 + return s.last 366 + } 367 + 368 + func streamStderr(pipe io.Reader, mStatus prefixedMenuItem) *stderrLogger { 369 + sl := &stderrLogger{} 370 + go func() { 371 + scanner := bufio.NewScanner(pipe) 372 + for scanner.Scan() { 373 + line := scanner.Text() 374 + log.Print(line) 375 + sl.mu.Lock() 376 + sl.last = line 377 + sl.mu.Unlock() 378 + if trimmed := strings.TrimSpace(line); trimmed != "" { 379 + mStatus.SetTitle(trimmed) 380 + } 381 + } 382 + }() 383 + return sl 384 + } 385 + 386 + func exitCode(err error) int { 387 + if exitErr, ok := err.(*exec.ExitError); ok { 388 + return exitErr.ExitCode() 389 + } 390 + return -1 391 + } 392 + 393 + func classifyError(err error, lastStderr string) (string, int) { 394 + code := exitCode(err) 395 + if code == 12 { 396 + return "Wrong password", code 397 + } 398 + if lastStderr != "" { 399 + var msg struct { 400 + Message string `json:"message"` 401 + } 402 + if json.Unmarshal([]byte(lastStderr), &msg) == nil && msg.Message != "" { 403 + return msg.Message, code 404 + } 405 + return lastStderr, code 406 + } 407 + if err != nil { 408 + return err.Error(), code 409 + } 410 + return "", code 411 + } 412 + 413 + func runResticOnce(idx int, prof Profile, mStatus prefixedMenuItem, args ...string) (string, error) { 414 + cmd := resticCmd(prof, args...) 415 + var stdout strings.Builder 416 + cmd.Stdout = &stdout 417 + stderrPipe, _ := cmd.StderrPipe() 418 + setProfileBusyCmd(idx, cmd) 419 + 420 + if err := cmd.Start(); err != nil { 421 + log.Printf("[%s] start failed: %v", prof.displayName(), err) 422 + return err.Error(), err 423 + } 424 + 425 + sl := streamStderr(stderrPipe, mStatus) 426 + err := cmd.Wait() 427 + if out := stdout.String(); out != "" { 428 + log.Print(out) 429 + } 430 + if err == nil { 431 + log.Printf("[%s] done: restic %s", prof.displayName(), args[0]) 432 + return "", nil 433 + } 434 + msg, code := classifyError(err, sl.lastLine()) 435 + if msg != "" { 436 + mStatus.SetTitle(msg) 437 + } 438 + log.Printf("[%s] exit: %v (code %d)", prof.displayName(), err, code) 439 + return msg, err 440 + } 441 + 442 + func retryLockEnabled(prof Profile) bool { 443 + return prof.RetryLock != "" && prof.RetryLock != "0" 444 + } 445 + 446 + func retryUnlock(idx int, prof Profile, mStatus prefixedMenuItem) { 447 + log.Printf("[%s] locked, running unlock and retrying", prof.displayName()) 448 + mStatus.SetTitle("Unlocking repository...") 449 + runResticOnce(idx, prof, mStatus, "unlock") 450 + } 451 + 452 + func runRestic(idx int, prof Profile, mStatus prefixedMenuItem, args ...string) (string, error) { 453 + if retryLockEnabled(prof) { 454 + args = append(args, "--retry-lock", prof.RetryLock) 455 + } 456 + msg, err := runResticOnce(idx, prof, mStatus, args...) 457 + if err != nil && exitCode(err) == 11 && retryLockEnabled(prof) { 458 + retryUnlock(idx, prof, mStatus) 459 + msg, err = runResticOnce(idx, prof, mStatus, args...) 460 + } 461 + return msg, err 462 + } 463 + 464 + func formatSize(sz uint64) string { 465 + switch { 466 + case sz >= 1e9: 467 + return fmt.Sprintf("%.1f GB", float64(sz)/1e9) 468 + case sz >= 1e6: 469 + return fmt.Sprintf("%.1f MB", float64(sz)/1e6) 470 + case sz >= 1e3: 471 + return fmt.Sprintf("%.0f KB", float64(sz)/1e3) 472 + default: 473 + return fmt.Sprintf("%d bytes", sz) 474 + } 475 + } 476 + 477 + func doBackupOnce(idx int, mStatus prefixedMenuItem, prof Profile, args []string) (bool, int) { 478 + cmd := resticCmd(prof, args...) 479 + stdoutPipe, _ := cmd.StdoutPipe() 480 + stderrPipe, _ := cmd.StderrPipe() 481 + setProfileBusyCmd(idx, cmd) 482 + 483 + if err := cmd.Start(); err != nil { 484 + log.Printf("[%s] start failed: %v", prof.displayName(), err) 485 + setProfileFailed(idx, err.Error()) 486 + return false, -1 487 + } 488 + 489 + sl := streamStderr(stderrPipe, mStatus) 490 + 491 + scanner := bufio.NewScanner(stdoutPipe) 492 + for scanner.Scan() { 493 + line := scanner.Text() 494 + 495 + var msg struct { 496 + Type string `json:"message_type"` 497 + Percent float64 `json:"percent_done"` 498 + Total uint64 `json:"total_bytes"` 499 + Bytes uint64 `json:"bytes_done"` 500 + TotalFiles uint64 `json:"total_files"` 501 + FilesDone uint64 `json:"files_done"` 502 + } 503 + if json.Unmarshal([]byte(line), &msg) != nil || msg.Type == "" { 504 + log.Print(line) 505 + continue 506 + } 507 + if msg.Type == "status" { 508 + switch { 509 + case msg.Total > 0: 510 + mStatus.SetTitle(fmt.Sprintf("%d%% completed, %s of %s", 511 + int(msg.Percent*100), formatSize(msg.Bytes), formatSize(msg.Total))) 512 + case msg.TotalFiles > 0: 513 + mStatus.SetTitle(fmt.Sprintf("Scanning: %d / %d files", 514 + msg.FilesDone, msg.TotalFiles)) 515 + default: 516 + mStatus.SetTitle(fmt.Sprintf("Scanning: %d files", msg.FilesDone)) 517 + } 518 + } else { 519 + log.Print(line) 520 + } 521 + } 522 + 523 + if err := cmd.Wait(); err != nil { 524 + msg, code := classifyError(err, sl.lastLine()) 525 + log.Printf("[%s] exit: %v (code %d)", prof.displayName(), err, code) 526 + if code == 3 { 527 + log.Printf("[%s] backup completed with warnings (some files could not be read)", prof.displayName()) 528 + return true, 3 529 + } 530 + setProfileFailed(idx, msg) 531 + return false, code 532 + } 533 + log.Printf("[%s] done: backup", prof.displayName()) 534 + return true, 0 535 + } 536 + 537 + func doBackup(idx int, mStatus prefixedMenuItem, prof Profile, scheduled bool) bool { 538 + args := []string{"backup", "--json"} 539 + if retryLockEnabled(prof) { 540 + args = append(args, "--retry-lock", prof.RetryLock) 541 + } 542 + args = append(args, prof.Backup.Args...) 543 + if scheduled { 544 + args = append(args, prof.Backup.ArgsScheduled...) 545 + } 546 + args = append(args, prof.Backup.Paths...) 547 + 548 + ok, code := doBackupOnce(idx, mStatus, prof, args) 549 + if !ok && code == 11 && retryLockEnabled(prof) { 550 + retryUnlock(idx, prof, mStatus) 551 + mStatus.SetTitle("Backing up...") 552 + setProfileFailed(idx, "") 553 + ok, code = doBackupOnce(idx, mStatus, prof, args) 554 + } 555 + if !scheduled { 556 + switch { 557 + case !ok: 558 + notifyError("Backup", getProfileFailStatus(idx)) 559 + case code == 3: 560 + notifyError("Backup", "Completed with warnings: some files could not be read") 561 + default: 562 + notifySuccess("Backup") 563 + } 564 + } 565 + return ok 566 + } 567 + 568 + func runBackup(idx int, mStatus prefixedMenuItem, prof Profile, onDone func()) { 569 + if p, _ := findRestic(); p == "" { 570 + return 571 + } 572 + if isProfileBusy(idx) { 573 + return 574 + } 575 + 576 + setProfileFailed(idx, "") 577 + mStatus.SetTitle("Backing up...") 578 + setProfileBusy(idx, true) 579 + defer onDone() 580 + defer setProfileBusy(idx, false) 581 + 582 + doBackup(idx, mStatus, prof, false) 583 + } 584 + 585 + func runScheduled(idx int, mStatus prefixedMenuItem, prof Profile, onDone func()) { 586 + if p, _ := findRestic(); p == "" { 587 + return 588 + } 589 + if isProfileBusy(idx) { 590 + return 591 + } 592 + 593 + setProfileFailed(idx, "") 594 + setProfileBusy(idx, true) 595 + defer onDone() 596 + defer setProfileBusy(idx, false) 597 + 598 + failed := false 599 + 600 + if prof.Schedule.BackupEnabled() { 601 + mStatus.SetTitle("Backing up...") 602 + if !doBackup(idx, mStatus, prof, true) { 603 + notifyError("Schedule", getProfileFailStatus(idx)) 604 + return 605 + } 606 + } 607 + 608 + if prof.Schedule.Prune && len(prof.Prune.Args) > 0 { 609 + mStatus.SetTitle("Pruning repository...") 610 + if msg, err := runRestic(idx, prof, mStatus, forgetArgs(prof)...); err != nil { 611 + setProfileFailed(idx, msg) 612 + failed = true 613 + } 614 + } 615 + if prof.Schedule.Check { 616 + mStatus.SetTitle("Checking repository...") 617 + if msg, err := runRestic(idx, prof, mStatus, checkArgs(prof)...); err != nil { 618 + setProfileFailed(idx, msg) 619 + failed = true 620 + } 621 + } 622 + 623 + if failed { 624 + notifyError("Schedule", getProfileFailStatus(idx)) 625 + } else { 626 + notifySuccess("Schedule") 627 + } 628 + } 629 + 630 + func forgetArgs(prof Profile) []string { 631 + return append([]string{"forget", "--prune"}, prof.Prune.Args...) 632 + } 633 + 634 + func checkArgs(prof Profile) []string { 635 + return append([]string{"check"}, prof.Check.Args...) 636 + } 637 + 638 + func isProfileMounted(idx int) bool { 639 + state.mu.Lock() 640 + defer state.mu.Unlock() 641 + return state.mountCmds[idx] != nil 642 + } 643 + 644 + func startMount(idx int, prof Profile, mMount *systray.MenuItem, onDone func()) { 645 + dir, err := os.MkdirTemp("", "restray-mount-") 646 + if err != nil { 647 + return 648 + } 649 + 650 + mountArgs := append([]string{"mount", "--no-lock"}, prof.Mount.Args...) 651 + mountArgs = append(mountArgs, dir) 652 + cmd := resticCmd(prof, mountArgs...) 653 + var stderr strings.Builder 654 + cmd.Stderr = &stderr 655 + 656 + if err := cmd.Start(); err != nil { 657 + os.Remove(dir) 658 + notifyError("Mount", err.Error()) 659 + onDone() 660 + return 661 + } 662 + 663 + state.mu.Lock() 664 + state.mountCmds[idx] = cmd 665 + state.mu.Unlock() 666 + 667 + mMount.SetTitle("Unmount") 668 + 669 + done := make(chan error, 1) 670 + go func() { done <- cmd.Wait() }() 671 + 672 + mounted := false 673 + for i := 0; i < 20; i++ { 674 + select { 675 + case <-done: 676 + goto cleanup 677 + case <-time.After(250 * time.Millisecond): 678 + } 679 + entries, _ := os.ReadDir(dir) 680 + if len(entries) > 0 { 681 + mounted = true 682 + break 683 + } 684 + } 685 + if mounted { 686 + openFile(dir) 687 + <-done 688 + } 689 + cleanup: 690 + 691 + state.mu.Lock() 692 + delete(state.mountCmds, idx) 693 + stopped := state.mountStopping[idx] 694 + delete(state.mountStopping, idx) 695 + state.mu.Unlock() 696 + os.Remove(dir) 697 + 698 + if msg := stderr.String(); msg != "" && !stopped { 699 + notifyError("Mount", strings.TrimSpace(msg)) 700 + } 701 + 702 + onDone() 703 + } 704 + 705 + func stopProfileMount(idx int) { 706 + state.mu.Lock() 707 + defer state.mu.Unlock() 708 + if cmd := state.mountCmds[idx]; cmd != nil && cmd.Process != nil { 709 + state.mountStopping[idx] = true 710 + interruptProcess(cmd.Process) 711 + } 712 + } 713 + 714 + func stopAllMounts() { 715 + state.mu.Lock() 716 + defer state.mu.Unlock() 717 + for idx, cmd := range state.mountCmds { 718 + if cmd != nil && cmd.Process != nil { 719 + state.mountStopping[idx] = true 720 + interruptProcess(cmd.Process) 721 + } 722 + } 723 + } 724 + 725 + func init() { 726 + beeep.AppName = "Restray" 727 + } 728 + 729 + func notifyMode() string { 730 + state.mu.Lock() 731 + defer state.mu.Unlock() 732 + return state.notifications 733 + } 734 + 735 + func notifyError(operation, msg string) { 736 + mode := notifyMode() 737 + if mode != "all" && mode != "errors" { 738 + return 739 + } 740 + beeep.Alert(operation+" failed", msg, alertIcon) 741 + } 742 + 743 + func notifySuccess(operation string) { 744 + if notifyMode() != "all" { 745 + return 746 + } 747 + beeep.Notify(operation+" complete", operation+" completed successfully", "") 748 + }
restray_windows_386.syso

This is a binary file and will not be displayed.

restray_windows_amd64.syso

This is a binary file and will not be displayed.

+25
templates/config.toml
··· 1 + # Restray configuration 2 + # Configuration reference: https://tangled.org/devins.page/restray#configuration 3 + 4 + [general] 5 + # manage_restic = false 6 + # notifications = "none" 7 + 8 + [[profile]] 9 + name = "default" 10 + # env_file = "{{ENV_FILE}}" 11 + 12 + [profile.schedule] 13 + # cron = "" 14 + # on_battery = false 15 + # backup = true 16 + # prune = false 17 + # check = false 18 + 19 + [profile.backup] 20 + paths = [] 21 + # args = ["--exclude-caches", "--exclude", "*.tmp"] 22 + # args_scheduled = ["--tag", "scheduled"] 23 + 24 + [profile.prune] 25 + # args = ["--keep-last", "4", "--keep-hourly", "24", "--keep-daily", "7", "--keep-weekly", "4", "--keep-monthly", "12"]
+7
templates/default.env
··· 1 + # Restray environment 2 + # Restic scripting documentation: https://restic.readthedocs.io/en/stable/075_scripting.html 3 + 4 + RESTIC_REPOSITORY= 5 + RESTIC_PASSWORD= 6 + # RESTIC_PASSWORD_FILE=/path/to/passwordfile 7 + # RESTIC_PASSWORD_COMMAND=secret-tool lookup restic repo
+692
tray.go
··· 1 + package main 2 + 3 + import ( 4 + "fmt" 5 + "log" 6 + "os" 7 + "runtime" 8 + "strings" 9 + "sync" 10 + "time" 11 + 12 + "fyne.io/systray" 13 + "github.com/distatus/battery" 14 + hcron "github.com/lnquy/cron" 15 + "github.com/robfig/cron/v3" 16 + ) 17 + 18 + const ( 19 + maxProfiles = 8 20 + maxMenuWidth = 48 // truncate since Windows menus never shrink after expanding 21 + ) 22 + 23 + var cronDescriptor, _ = hcron.NewDescriptor() 24 + 25 + func describeCron(expr string) string { 26 + desc, err := cronDescriptor.ToDescription(expr, hcron.Locale_en) 27 + if err != nil { 28 + return expr 29 + } 30 + desc = strings.TrimSpace(desc) 31 + if len(desc) > 0 { 32 + desc = strings.ToLower(desc[:1]) + desc[1:] 33 + } 34 + return desc 35 + } 36 + 37 + type prefixedMenuItem struct { 38 + *systray.MenuItem 39 + prefix string 40 + } 41 + 42 + func (p prefixedMenuItem) SetTitle(title string) { 43 + title = p.prefix + title 44 + if len(title) > maxMenuWidth { 45 + title = title[:maxMenuWidth-1] + "…" 46 + } 47 + p.MenuItem.SetTitle(title) 48 + } 49 + 50 + type profileState struct { 51 + errMsg string 52 + repoErr string 53 + needsInit bool 54 + } 55 + 56 + var ( 57 + profileMu sync.Mutex 58 + activeProfile int 59 + profileStates []profileState 60 + profileEntryIDs map[int][]cron.EntryID 61 + ) 62 + 63 + func getActiveProfile() int { 64 + profileMu.Lock() 65 + defer profileMu.Unlock() 66 + return activeProfile 67 + } 68 + 69 + func setProfileFailed(idx int, status string) { 70 + state.mu.Lock() 71 + if status == "" { 72 + delete(state.failStatus, idx) 73 + } else { 74 + state.failStatus[idx] = status 75 + } 76 + state.mu.Unlock() 77 + } 78 + 79 + func getProfileFailStatus(idx int) string { 80 + state.mu.Lock() 81 + defer state.mu.Unlock() 82 + return state.failStatus[idx] 83 + } 84 + 85 + func anyError() bool { 86 + state.mu.Lock() 87 + hasFail := len(state.failStatus) > 0 88 + state.mu.Unlock() 89 + if hasFail { 90 + return true 91 + } 92 + profileMu.Lock() 93 + defer profileMu.Unlock() 94 + for _, p := range profileStates { 95 + if p.errMsg != "" || p.repoErr != "" { 96 + return true 97 + } 98 + } 99 + return false 100 + } 101 + 102 + func onReady() { 103 + firstLaunch := !fileExists(configPath()) 104 + setIconAnimated("idle") 105 + systray.SetTooltip("Restray") 106 + 107 + mProfile := systray.AddMenuItem("Restray", "") 108 + mProfile.Disable() 109 + var profileItems [maxProfiles]*systray.MenuItem 110 + for i := range profileItems { 111 + profileItems[i] = mProfile.AddSubMenuItem("", "") 112 + profileItems[i].Hide() 113 + } 114 + 115 + setProfileTitle := func(cfg Config, idx int) { 116 + if len(cfg.Profile) > 1 { 117 + mProfile.SetTitle("Profile - " + cfg.Profile[idx].displayName()) 118 + mProfile.Enable() 119 + } else { 120 + mProfile.SetTitle("Restray") 121 + mProfile.Disable() 122 + } 123 + } 124 + 125 + markActiveProfile := func(active int, count int) { 126 + for i := 0; i < count && i < maxProfiles; i++ { 127 + if i == active { 128 + profileItems[i].Check() 129 + profileItems[i].Disable() 130 + } else { 131 + profileItems[i].Uncheck() 132 + profileItems[i].Enable() 133 + } 134 + } 135 + } 136 + 137 + mGlobalStatus := prefixedMenuItem{systray.AddMenuItem("Loading...", ""), ""} 138 + mGlobalStatus.Disable() 139 + var mStatusItems [maxProfiles]*systray.MenuItem 140 + for i := range mStatusItems { 141 + mStatusItems[i] = systray.AddMenuItem("", "") 142 + mStatusItems[i].Disable() 143 + mStatusItems[i].Hide() 144 + } 145 + 146 + systray.AddSeparator() 147 + mDownload := systray.AddMenuItem("Download Restic", "Download restic binary") 148 + mDownload.Hide() 149 + mUpdate := systray.AddMenuItem("", "Update restic binary") 150 + mUpdate.Hide() 151 + mBackup := systray.AddMenuItem("Run Backup Now", "Run a backup immediately") 152 + mBackup.Hide() 153 + mCancel := systray.AddMenuItem("Cancel", "Cancel running operation") 154 + mCancel.Hide() 155 + mInit := systray.AddMenuItem("Initialize Repository", "Initialize a new restic repository") 156 + mInit.Hide() 157 + mRepo := systray.AddMenuItem("Repository", "Repository operations") 158 + mPrune := mRepo.AddSubMenuItem("Prune", "Remove old snapshots and free space") 159 + mCheck := mRepo.AddSubMenuItem("Check", "Verify repository integrity") 160 + mUnlock := mRepo.AddSubMenuItem("Unlock", "Remove stale repository locks") 161 + mMount := mRepo.AddSubMenuItem("Mount", "Mount repository and browse snapshots") 162 + mConsole := mRepo.AddSubMenuItem("Shell", "Open terminal with repository environment") 163 + mConfigure := systray.AddMenuItem("Configure", "Restray settings") 164 + mFDA := mConfigure.AddSubMenuItem("Grant Full Disk Access", "Open System Settings to grant Full Disk Access") 165 + mFDA.Hide() 166 + mSettings := mConfigure.AddSubMenuItem("Edit Config File", "Open config file in editor") 167 + mEnv := mConfigure.AddSubMenuItem("Edit Env File", "Open env file in editor") 168 + mFixPerms := mConfigure.AddSubMenuItem("Fix Permissions", "Config directory, config file, or env file permissions too open") 169 + mFixPerms.Hide() 170 + mLog := mConfigure.AddSubMenuItem("View Log", "Open log file in editor") 171 + mFolder := mConfigure.AddSubMenuItem("Open Folder", "Open folder in file manager") 172 + systray.AddSeparator() 173 + mQuit := systray.AddMenuItem("Quit", "Quit Restray") 174 + 175 + sched := cron.New() 176 + var applyConfig func() 177 + 178 + state.onBusyChanged = func(bool) { 179 + idx := getActiveProfile() 180 + if isProfileBusy(idx) { 181 + mCancel.Show() 182 + mBackup.Hide() 183 + mRepo.Disable() 184 + } else { 185 + mCancel.Hide() 186 + } 187 + } 188 + 189 + createOrEdit := func(m *systray.MenuItem, label, path string) { 190 + if _, err := os.Stat(path); err != nil { 191 + m.SetTitle("Create " + label) 192 + } else { 193 + m.SetTitle("Edit " + label) 194 + } 195 + } 196 + 197 + hideActions := func() { 198 + mBackup.Hide() 199 + mInit.Hide() 200 + mDownload.Hide() 201 + mUpdate.Hide() 202 + mRepo.Disable() 203 + } 204 + 205 + doDownload := func() { 206 + err := downloadRestic(mGlobalStatus) 207 + if err != nil { 208 + setIconAnimated("fail") 209 + mGlobalStatus.SetTitle("Download failed: " + err.Error()) 210 + mDownload.Show() 211 + return 212 + } 213 + applyConfig() 214 + } 215 + 216 + selectedProfile := func() Profile { 217 + cfg := loadConfig() 218 + idx := getActiveProfile() 219 + if idx < len(cfg.Profile) { 220 + return cfg.Profile[idx] 221 + } 222 + return cfg.Profile[0] 223 + } 224 + 225 + statusItem := func(idx int) prefixedMenuItem { 226 + cfg := loadConfig() 227 + prefix := "" 228 + if len(cfg.Profile) > 1 && idx < len(cfg.Profile) { 229 + prefix = cfg.Profile[idx].displayName() + " - " 230 + } 231 + return prefixedMenuItem{mStatusItems[idx], prefix} 232 + } 233 + 234 + profileStatusText := func(cfg Config, i int) string { 235 + profileMu.Lock() 236 + if i >= len(profileStates) { 237 + profileMu.Unlock() 238 + return "" 239 + } 240 + ps := profileStates[i] 241 + eids := profileEntryIDs[i] 242 + profileMu.Unlock() 243 + prof := cfg.Profile[i] 244 + 245 + prefix := "" 246 + if len(cfg.Profile) > 1 { 247 + prefix = prof.displayName() + " - " 248 + } 249 + 250 + switch { 251 + case ps.errMsg != "": 252 + return prefix + ps.errMsg 253 + case ps.repoErr != "": 254 + return prefix + ps.repoErr 255 + default: 256 + paused := !prof.Schedule.OnBattery && onBatteryPower() 257 + if prof.Schedule.Cron == "" { 258 + return prefix + "Unscheduled" 259 + } 260 + if paused { 261 + return prefix + "Paused (battery)" 262 + } 263 + next := formatNextFor(sched, eids) 264 + display := cfg.General.ScheduleDisplay 265 + switch display { 266 + case "none", "hidden": 267 + if next != "" { 268 + return prefix + next 269 + } 270 + return prefix + "Scheduled" 271 + case "cron": 272 + if next != "" { 273 + return prefix + next + " - " + prof.Schedule.Cron 274 + } 275 + return prefix + prof.Schedule.Cron 276 + default: 277 + schedule := describeCron(prof.Schedule.Cron) 278 + if next != "" { 279 + return prefix + next + " - " + schedule 280 + } 281 + return prefix + schedule 282 + } 283 + } 284 + } 285 + 286 + updateAllStatusItems := func(cfg Config) { 287 + mGlobalStatus.Hide() 288 + for i := 0; i < len(cfg.Profile) && i < maxProfiles; i++ { 289 + if !isProfileBusy(i) { 290 + failMsg := getProfileFailStatus(i) 291 + if failMsg != "" { 292 + if len(cfg.Profile) > 1 { 293 + failMsg = cfg.Profile[i].displayName() + " - " + failMsg 294 + } 295 + if len(failMsg) > maxMenuWidth { 296 + failMsg = failMsg[:maxMenuWidth-1] + "…" 297 + } 298 + mStatusItems[i].SetTitle(failMsg) 299 + } else { 300 + mStatusItems[i].SetTitle(profileStatusText(cfg, i)) 301 + } 302 + } 303 + mStatusItems[i].Show() 304 + } 305 + for i := len(cfg.Profile); i < maxProfiles; i++ { 306 + mStatusItems[i].Hide() 307 + } 308 + } 309 + 310 + applyProfileUI := func(cfg Config) { 311 + profileMu.Lock() 312 + idx := activeProfile 313 + if idx >= len(profileStates) || idx >= len(cfg.Profile) { 314 + profileMu.Unlock() 315 + return 316 + } 317 + ps := profileStates[idx] 318 + profileMu.Unlock() 319 + prof := cfg.Profile[idx] 320 + 321 + createOrEdit(mEnv, "Env File", prof.EnvFile) 322 + if envFilesInsecure(cfg.Profile) { 323 + mFixPerms.Show() 324 + } else { 325 + mFixPerms.Hide() 326 + } 327 + 328 + mBackup.Hide() 329 + mInit.Hide() 330 + mRepo.Disable() 331 + 332 + if isProfileBusy(idx) { 333 + mCancel.Show() 334 + } else { 335 + mCancel.Hide() 336 + switch { 337 + case ps.errMsg != "": 338 + case ps.repoErr != "": 339 + if ps.needsInit { 340 + mInit.Show() 341 + } 342 + default: 343 + mRepo.Enable() 344 + mBackup.Show() 345 + mBackup.Enable() 346 + if runtime.GOOS == "windows" { 347 + mMount.Hide() 348 + } else if isProfileMounted(idx) { 349 + mMount.SetTitle("Unmount") 350 + } else { 351 + mMount.SetTitle("Mount") 352 + } 353 + } 354 + } 355 + 356 + updateAllStatusItems(cfg) 357 + } 358 + 359 + applyConfig = func() { 360 + if isAnyBusy() { 361 + cfg := loadConfig() 362 + profileMu.Lock() 363 + if activeProfile >= len(cfg.Profile) { 364 + activeProfile = 0 365 + } 366 + activeIdx := activeProfile 367 + profileMu.Unlock() 368 + markActiveProfile(activeIdx, len(cfg.Profile)) 369 + setProfileTitle(cfg, activeIdx) 370 + updateAllStatusItems(cfg) 371 + applyProfileUI(cfg) 372 + return 373 + } 374 + cfg := loadConfig() 375 + state.mu.Lock() 376 + state.notifications = strings.ToLower(cfg.General.Notifications) 377 + state.mu.Unlock() 378 + sched.Stop() 379 + sched = cron.New() 380 + 381 + createOrEdit(mSettings, "Config File", configPath()) 382 + 383 + mDownload.Hide() 384 + mUpdate.Hide() 385 + 386 + resticPath, managed := findRestic() 387 + 388 + if resticPath == "" && cfg.General.ManageRestic { 389 + mGlobalStatus.SetTitle("Downloading restic...") 390 + mGlobalStatus.Show() 391 + go doDownload() 392 + return 393 + } 394 + if resticPath == "" { 395 + setIconAnimated("fail") 396 + mGlobalStatus.SetTitle("Restic not found") 397 + mGlobalStatus.Show() 398 + hideActions() 399 + mDownload.Show() 400 + mProfile.SetTitle("Restray") 401 + mProfile.Disable() 402 + return 403 + } 404 + 405 + if needsFullDiskAccess() { 406 + mFDA.Show() 407 + } else { 408 + mFDA.Hide() 409 + } 410 + 411 + profileMu.Lock() 412 + profileStates = make([]profileState, len(cfg.Profile)) 413 + profileEntryIDs = make(map[int][]cron.EntryID) 414 + profileMu.Unlock() 415 + 416 + for i, prof := range cfg.Profile { 417 + var ps profileState 418 + ps.errMsg = prof.configError() 419 + if ps.errMsg == "" { 420 + rs := repoStatus(prof) 421 + ps.repoErr = rs.errMsg 422 + ps.needsInit = rs.needsInit 423 + } 424 + 425 + label := prof.displayName() 426 + if ps.errMsg != "" { 427 + label += " - " + ps.errMsg 428 + } else if ps.repoErr != "" { 429 + label += " - " + ps.repoErr 430 + } 431 + 432 + profileMu.Lock() 433 + profileStates[i] = ps 434 + profileMu.Unlock() 435 + 436 + if i < maxProfiles { 437 + profileItems[i].SetTitle(label) 438 + profileItems[i].Show() 439 + } 440 + 441 + if ps.errMsg == "" && ps.repoErr == "" && prof.Schedule.Cron != "" { 442 + idx := i 443 + eid, err := sched.AddFunc(prof.Schedule.Cron, func() { 444 + current := loadConfig() 445 + if idx >= len(current.Profile) { 446 + return 447 + } 448 + if !current.Profile[idx].Schedule.OnBattery && onBatteryPower() { 449 + log.Printf("[%s] skipping scheduled backup: on battery power", current.Profile[idx].displayName()) 450 + return 451 + } 452 + runScheduled(idx, statusItem(idx), current.Profile[idx], applyConfig) 453 + }) 454 + if err != nil { 455 + log.Printf("[%s] invalid cron expression %q: %v", prof.displayName(), prof.Schedule.Cron, err) 456 + ps.errMsg = "Invalid cron: " + prof.Schedule.Cron 457 + profileMu.Lock() 458 + profileStates[i] = ps 459 + profileMu.Unlock() 460 + } else { 461 + profileMu.Lock() 462 + profileEntryIDs[idx] = append(profileEntryIDs[idx], eid) 463 + profileMu.Unlock() 464 + } 465 + } 466 + } 467 + 468 + for i := len(cfg.Profile); i < maxProfiles; i++ { 469 + profileItems[i].Hide() 470 + profileItems[i].Uncheck() 471 + } 472 + 473 + profileMu.Lock() 474 + if activeProfile >= len(cfg.Profile) { 475 + activeProfile = 0 476 + } 477 + activeIdx := activeProfile 478 + profileMu.Unlock() 479 + 480 + markActiveProfile(activeIdx, len(cfg.Profile)) 481 + setProfileTitle(cfg, activeIdx) 482 + 483 + if anyError() { 484 + setIconAnimated("fail") 485 + } else { 486 + setIconAnimated("idle") 487 + } 488 + 489 + sched.Start() 490 + applyProfileUI(cfg) 491 + 492 + if managed { 493 + go checkResticUpdate(resticPath, cfg.General.ManageRestic, mUpdate, mGlobalStatus, applyConfig) 494 + } 495 + } 496 + 497 + applyConfig() 498 + if firstLaunch && needsFullDiskAccess() { 499 + go promptFullDiskAccess() 500 + } 501 + watchConfig(applyConfig) 502 + 503 + go func() { 504 + for range time.NewTicker(24 * time.Hour).C { 505 + resticPath, managed := findRestic() 506 + if managed && !isAnyBusy() { 507 + cfg := loadConfig() 508 + checkResticUpdate(resticPath, cfg.General.ManageRestic, mUpdate, mGlobalStatus, applyConfig) 509 + } 510 + } 511 + }() 512 + 513 + go func() { 514 + prev := onBatteryPower() 515 + for range time.NewTicker(60 * time.Second).C { 516 + cur := onBatteryPower() 517 + if cur != prev { 518 + prev = cur 519 + if !isAnyBusy() { 520 + applyProfileUI(loadConfig()) 521 + continue 522 + } 523 + } 524 + updateAllStatusItems(loadConfig()) 525 + } 526 + }() 527 + 528 + repoOp := func(status string, args ...string) { 529 + idx := getActiveProfile() 530 + if idx >= maxProfiles || isProfileBusy(idx) { 531 + return 532 + } 533 + prof := selectedProfile() 534 + ms := statusItem(idx) 535 + go func() { 536 + ms.SetTitle(status) 537 + setProfileBusy(idx, true) 538 + msg, err := runRestic(idx, prof, ms, args...) 539 + setProfileBusy(idx, false) 540 + if err != nil { 541 + setProfileFailed(idx, msg) 542 + notifyError(args[0], msg) 543 + } else { 544 + setProfileFailed(idx, "") 545 + notifySuccess(args[0]) 546 + } 547 + applyConfig() 548 + }() 549 + } 550 + 551 + go func() { 552 + for { 553 + select { 554 + case <-mBackup.ClickedCh: 555 + idx := getActiveProfile() 556 + if idx < maxProfiles && !isProfileBusy(idx) { 557 + go runBackup(idx, statusItem(idx), selectedProfile(), applyConfig) 558 + } 559 + case <-mCancel.ClickedCh: 560 + cancelProfile(getActiveProfile()) 561 + case <-mPrune.ClickedCh: 562 + prof := selectedProfile() 563 + if len(prof.Prune.Args) > 0 { 564 + repoOp("Pruning repository...", forgetArgs(prof)...) 565 + } 566 + case <-mCheck.ClickedCh: 567 + repoOp("Checking repository...", checkArgs(selectedProfile())...) 568 + case <-mUnlock.ClickedCh: 569 + repoOp("Unlocking repository...", "unlock") 570 + case <-mInit.ClickedCh: 571 + repoOp("Initializing repository...", "init") 572 + case <-mMount.ClickedCh: 573 + idx := getActiveProfile() 574 + if isProfileMounted(idx) { 575 + stopProfileMount(idx) 576 + } else { 577 + go startMount(idx, selectedProfile(), mMount, applyConfig) 578 + } 579 + case <-mConsole.ClickedCh: 580 + cfg := loadConfig() 581 + openConsole(selectedProfile(), len(cfg.Profile), cfg.General.Terminal, "") 582 + case <-mDownload.ClickedCh: 583 + if !isAnyBusy() { 584 + hideActions() 585 + go doDownload() 586 + } 587 + case <-mUpdate.ClickedCh: 588 + if !isAnyBusy() { 589 + hideActions() 590 + go doDownload() 591 + } 592 + case <-mSettings.ClickedCh: 593 + ensureConfigFile() 594 + openInEditor(configPath()) 595 + case <-mEnv.ClickedCh: 596 + prof := selectedProfile() 597 + ensureEnvFile(prof.EnvFile) 598 + openInEditor(prof.EnvFile) 599 + case <-mFDA.ClickedCh: 600 + openFullDiskAccessSettings() 601 + case <-mFixPerms.ClickedCh: 602 + cfg := loadConfig() 603 + fixEnvFilePermissions(cfg.Profile) 604 + if envFilesInsecure(cfg.Profile) { 605 + mFixPerms.Show() 606 + } else { 607 + mFixPerms.Hide() 608 + } 609 + if !isAnyBusy() { 610 + applyConfig() 611 + } 612 + case <-mLog.ClickedCh: 613 + cfg := loadConfig() 614 + openConsole(selectedProfile(), len(cfg.Profile), cfg.General.Terminal, logPath()) 615 + case <-mFolder.ClickedCh: 616 + openFile(configDir()) 617 + case <-mQuit.ClickedCh: 618 + sched.Stop() 619 + stopAllMounts() 620 + systray.Quit() 621 + } 622 + } 623 + }() 624 + 625 + for i := 0; i < maxProfiles; i++ { 626 + idx := i 627 + go func() { 628 + for range profileItems[idx].ClickedCh { 629 + cfg := loadConfig() 630 + if idx >= len(cfg.Profile) { 631 + continue 632 + } 633 + profileMu.Lock() 634 + activeProfile = idx 635 + profileMu.Unlock() 636 + markActiveProfile(idx, len(cfg.Profile)) 637 + setProfileTitle(cfg, idx) 638 + applyProfileUI(cfg) 639 + } 640 + }() 641 + } 642 + } 643 + 644 + func formatNextFor(sched *cron.Cron, ids []cron.EntryID) string { 645 + if len(ids) == 0 { 646 + return "" 647 + } 648 + want := make(map[cron.EntryID]bool, len(ids)) 649 + for _, id := range ids { 650 + want[id] = true 651 + } 652 + var earliest time.Time 653 + for _, e := range sched.Entries() { 654 + if !want[e.ID] { 655 + continue 656 + } 657 + if earliest.IsZero() || e.Next.Before(earliest) { 658 + earliest = e.Next 659 + } 660 + } 661 + if earliest.IsZero() { 662 + return "" 663 + } 664 + now := time.Now() 665 + d := earliest.Sub(now) 666 + 667 + today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) 668 + tomorrow := today.AddDate(0, 0, 1) 669 + dayAfter := today.AddDate(0, 0, 2) 670 + 671 + switch { 672 + case d < time.Hour: 673 + return fmt.Sprintf("%dm", int(d.Minutes())) 674 + case earliest.After(today) && earliest.Before(tomorrow): 675 + return "Today " + earliest.Format("15:04") 676 + case earliest.After(tomorrow) && earliest.Before(dayAfter): 677 + return "Tomorrow " + earliest.Format("15:04") 678 + default: 679 + return earliest.Format("Jan 2 15:04") 680 + } 681 + } 682 + 683 + func onBatteryPower() bool { 684 + b, err := battery.Get(0) 685 + if _, ok := err.(battery.ErrFatal); ok { 686 + return false 687 + } 688 + if b == nil { 689 + return false 690 + } 691 + return b.State.Raw == battery.Discharging 692 + }