[
  {
    "path": "CONTRIBUTING.md",
    "content": "# How to contribute to the Blender Addon Updater.\n\nWe use the standard GitHub forking workflow. You can fork this repostiory, make your changes, and then merge them back with a pull request.\n\nTo ensure developers have easy access to the latest version of the addon updater, we only have a single branch. This should be the target of all pull requests.\n\n## Running tests\n\nIf you are making anything beyond a trivial change or documentation edit, please try to run the automated tests. There are two ways to run the tests, listed below. However these do not fully cover all behavior of the updater, especially the user interface flow, so be sure to manually test by installing your version of the addon too. Be sure to test the full update/revert flow, which you can manually force by artificially lowering the addon version number (e.g. to 0.1.0).\n\nWord to the wise: Don't shoot yourself in the foot! Be sure to make your edits to the updater in a place outside of the blender addons folder, and then install it like a normal addon (or use a script to copy the python files into place) between edits. This way you can test the full addon, without risking having your code delete (since the addon updater will indeed replace itself if you trigger an update/install version target).\n\n### Run tests from Blender text editor\n\nOpen up any (recent) version of blender, such that you have a console window visible (Windows users: Window > Toggle console, Mac/Linux: start blender from command line). Then, load in the `/tests/addon_updater_test.py` file. Press run, and verify \"All tests pass\" in the output.\n\n### Run tests on command line\n\nYou can run the tests by specifying it as a script to run on command line. For instance:\n\n```\ncd tests\nBlender -b -P addon_updater_test.py\ncd ../\n\n```\n\nYou should be able to validate you get tests outputs like so:\n\n```\n..\n----------------------------------------------------------------------\nRan 5 tests in 4.969s\n\nOK\n\n```\n\nIf there are any errors, please correct these before submitting a pull request!"
  },
  {
    "path": "LICENSE.txt",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    Blender Addon Updater\n    Copyright (C) 2016  Patrick W. Crawford\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    Blender Addon Updater Copyright (C) 2016  Patrick W. Crawford\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Blender Addon Updater\n\nWith this Python module, developers can create auto-checking for updates with their blender addons as well as one-click version installs. Updates are retrieved using GitHub's, GitLab's, or Bitbucket's code api, so the addon must have it's updated code available on GitHub/GitLab/Bitbucket and be making use of either tags or releases.\n\n![alt](/images/demo_gif.gif)\n\n\n:warning: **Please [see this page on known issues](https://github.com/CGCookie/blender-addon-updater/issues?q=is%3Aissue+is%3Aopen+label%3A%22Known+Issue%22), including available workarounds**\n\n*Want to add this code to your addon? [See this tutorial here](http://theduckcow.com/2016/addon-updater-tutorial/)*\n\nThis addon has been updated and still works from Blender 2.7 through 3.0, see [this section below](https://github.com/CGCookie/blender-addon-updater#blender-27-and-28).\n\n\n# Key Features\n*From the user perspective*\n\n- Uses [GitHub](https://github.com/), [GitLab](http://gitlab.com/) or [Bitbucket](https://bitbucket.org) repositories for source of versions and code\n  - All mentions of GitHub hereafter also apply to GitLab and Bitbucket unless called out separately\n- One-click to check if update is available\n- Auto-check: Ability to automatically check for updates in the background (user must enable)\n- Ability to set the interval of time between background checks (if auto-check enabled)\n- On a background check for update, contextual popup to tell user update available\n- One-click button to install update\n- Ability to install other (e.g. older or dev) versions of the addon\n\nWith this module, there are essentially 3 different configurations:\n- Connect an addon to a repository's releases & be notified when new releases are out and allow 1-click install (with an option to install master or another branch if enabled)\n- Connect an addon to a repository's releases & be notified when new releases are out, but direct user to website or specific download page instead of one-click installing (code doesn't even need to be hosted in connected repo in this scenario, as it's only using the releases metadata)\n- Connect an addon to a repository that doesn't have any releases, and allow use to 1-click install to a default branch and select from other explicitly included branches to install (does not us any version checking, will always pull the latest code even if the same)\n\n\n*Note the repository is not currently setup to be used with single Python file addons, this must be used with a zip-installed addon. It also assumes the use of the user preferences panel dedicated to the addon.*\n\n# High level setup\n\nThis module works by utilizing git releases on a repository. When a [release](https://github.com/CGCookie/blender-addon-updater/releases) or [tag](https://github.com/CGCookie/blender-addon-updater/tags) is created on GitHub/Bitbucket/Gitlab, the addon can check against the name of the tags/releases to know if an update is ready. The local addon version (in `bl_info`) is used to compare against that online name to know whether a more recent release is ready.\n\n![alt](/images/file_diagram.png)\n\nThis repository contains a fully working example of an addon with the updater code, but to integrate into another or existing addon, only the `addon_updater.py` and `addon_updater_ops.py` files are needed.\n\n`addon_updater.py` is an independent Python module that is the brains of the updater. It is implemented as a singleton, so the module-level variables are the same wherever it is imported. This file should not need to be modified by a developer looking to integrate auto-updating into an addon. Local \"private\" variables starting with _ have corresponding @property interfaces for interacting with the singleton instance's variables.\n\n`addon_updater_ops.py` links the states and settings of the `addon_updater.py` module and displays the according interface. This file is expected to be modified accordingly to be integrated with into another addon, and serves mostly as a working example of how to implement the updater code.\n\nIn this documentation, `addon_updater.py` is referred to by \"the Python Module\" and `addon_updater_ops.py` is referred to by \"the Operator File\".\n\n# About the example addon\n\nIncluded in this repository is an example addon which is integrates the auto-updater feature. It is currently linked to this repository and it's tags for testing. To use in your own addon, you only need the `addon_updater.py` and `addon_updater_ops.py` files. Then, you simply need to make the according function calls and create a release or tag on the corresponding repository.\n\n# Step-by-step as-is integration with existing addons\n\n*These steps are for the configuration that provides notifications of new releases and allows one-click installation*\n\n*These steps are also represented more thoroughly in [this text tutorial](http://theduckcow.com/2016/addon-updater-tutorial/)*\n\n1) Copy the Python Module (addon_updater.py) and the Operator File (addon_updater_ops.py) to the root folder of the existing addon folder\n\n2) import the updater operator file in `__init__.py` file e.g. `from . import addon_updater_ops` at the top with other module imports like `import bpy`\n\n3) In the register function of `__init__.py`, run the addon's def register() function by adding `addon_updater_ops.register(bl_info)`.\n  - Consider trying to place the updater register near the top of the addon's register function along with any preferences function so that if the user updates/reverts to a non-working version of the addon, they can still use the updater to restore backwards.\n\n4) Edit the according fields in the register function of the `addon_updater_ops.py` file. See the documentation below on these options, but at the bare minimum set the GitHub username and repository.\n  - Note that many of the settings are assigned in the `addon_updater_ops.py: register()` function to avoid having excess updater-related code in the addon's `__init__.py:register()` function, however because the updater module is shared across the addon, these settings could be made in either place.\n  - If using GitLab or Bitbucket, then you must also assign the according engine value, the rest is the same setup.\n\n5) To get the updater UI in the preferences draw panel and show all settings, add the line `addon_updater_ops.update_settings_ui(self,context)` to the end of the preferences class draw function.\n  - Be sure to import the Operator File if preferences are defined in a file other than the addon's `__init__.py` where already imported, e.g. via `from . import addon_updater_ops` like before\n\n-  Alternatively, a more condensed version of the UI preferences code may be draw with the sample function `addon_updater_ops.update_settings_ui_condensed(self, context, col)` instead of the above function.\n-  Note that the `col` input is optional, but allows you to add this function into an existing structure of rows/columns. This condensed UI doesn't show settings for interval (just an auto-check toggle, will use default interval) nor does it provide the backup-restoring or target-install operations.\n\n6) Add the needed blender properties to make the sample updater preferences UI work by copying over the blender properties from the sample demo addon's `DemoPreferences` class, located in the `__init__` file. Change the defaults as desired.\n\n```\n# addon updater preferences from `__init__`, be sure to copy all of them\n\n    auto_check_update = bpy.props.BoolProperty(\n        name = \"Auto-check for Update\",\n        description = \"If enabled, auto-check for updates using an interval\",\n        default = False,\n        )\n\n    ....\n\n    updater_interval_minutes = bpy.props.IntProperty(\n        name='Minutes',\n        description = \"Number of minutes between checking for updates\",\n        default=0,\n        min=0,\n        max=59\n        )\n```\n\n7) To support Blender version > 2.80, make one (not necessairly both) of these changes:\n\n    a. Add the decorator `@addon_updater_ops.make_annotations` before your addon's user preferences class ([see here](https://github.com/CGCookie/blender-addon-updater/blob/master/__init__.py#L76))\n\n    b. Call `make_annotations()`, passing your addon's user preferences class as an input, inside a register function ([see here](https://github.com/CGCookie/blender-addon-updater/blob/master/__init__.py#L152))\n\n8) Add the draw call to any according panel to indicate there is an update by adding this line to the end of the panel or window: `addon_updater_ops.update_notice_box_ui()`\n  - Again make sure to import the Operator File if this panel is defined in a file other than the addon's `__init__.py` file.\n  - Note that this function will only be called once per blender session, and will only do anything if auto-check is enabled, thus triggering a background check for update provided the interval of time has passed since the last check for update. This is safe to trigger from draw as it is launched in a background thread and will not hang blender.\n\n9) Ensure at least one [release or tag](https://help.github.com/articles/creating-releases/) exists on the GitHub repository\n  - As an alternative or in addition to using releases, the setting `updater.include_branches = True` in the `addon_updater_ops.py` register function allows you to update to specific git branches. You can then specify the list of branches for updating by using `updater.include_branche_list = ['branch','names']` for which the default is set to ['master']\n  - If no releases are found, the user preferences button will always show \"Update to Master\" without doing any version checking\n\n\n# Minimal example setup / use cases\n\nIf interested in implementing a purely customized UI implementation of this code, it is also possible to not use the included Operator File (addon_updater_ops.py). This section covers the typical steps required to accomplish the main tasks and what needs to be connected to an interface. This also exposes the underlying ideas implemented in the provided files.\n\n**Required settings** *Attributes to define before any other use case, to be defined in the registration of the addon*\n\n```\nfrom .addon_updater import Updater as updater # for example\n# updater.engine left at default assumes GitHub api/structure\nupdater.user = \"cgcookie\"\nupdater.repo = \"blender-addon-updater\"\nupdater.current_version = bl_info[\"version\"]\n```\n\n**Check for update** *(foreground using/blocking the main thread, after pressing an explicit \"check for update button\" - blender will hang)*\n\n```\nupdater.check_for_update_now()\n\n# convenience returns, values also saved internally to updater object\n(update_ready, version, link) = updater.check_for_update()\n\n```\n\n**Check for update** *(foreground using background thread, i.e. after pressing an explicit \"check for update button\")*\n\n```\nupdater.check_for_update_now(callback=None)\n```\n\n**Check for update** *(background using background thread, intended to trigger without notifying user - e.g. via auto-check after interval of time passed. Safe to call e.g. in a UI panel as it will at most run once per blender session)*\n\n```\nupdater.check_for_update_async(background_update_callback)\n# callback could be the function object to trigger a popup if result has updater.update_ready == True\n```\n\n**Update to newest version available** *(Must have already checked for an update. This uses/blocks the main thread)*\n\n```\nif updater.update_ready == True:\n  res = updater.run_update(force=False, revert_tag=None, callback=function_obj)\n  if res == 0:\n    print(\"Update ran successfully, restart blender\")\n  else:\n    print(\"Updater returned \" + str(res) + \", error occurred\")\nelif updater.update_ready == False:\n  print(\"No update available\")\nelif updater.update_ready == None:\n  print(\"You need to check for an update first\")\n```\n\n**Update to a target version of the addon** *(Perform the necessary error checking, updater.tags will == [] if a check has not yet been performed or releases are not found. Additional direct branch downloads will be inserted as the first entries if `updater.include_branches == True`. Pass in a function object function_obj to run code once the updater has finished if desired, or pass in None)*\n\n```\ntag_version = updater.tags[2] # or otherwise select a valid tag\nres = updater.run_update(force=False, revert_tag=None, callback=function_obj)\nif res == 0:\n  print(\"Update ran successfully, restart blender\")\nelse:\n  print(\"Updater returned \" + str(res) + \", error occurred\")\n```\n\n\nIf utilizing updater.include_branches, you can grab the latest release tag by skipping the branches included (which appear first in the tags list)\n\n```\nn = len(updater.include_branch_list)\ntag_version = updater.tags[n] # or otherwise select a valid tag\nres = updater.run_update(force=False, revert_tag=None, callback=function_obj)\nif res == 0:\n  print(\"Update ran successfully, restart blender\")\nelse:\n  print(\"Updater returned \" + str(res) + \", error occurred\")\n```\n\n\n\n# addon_updater module settings\n\nThis section provides documentation for all of the addon_updater module settings available and required. These are the settings applied directly to the addon_updater module itself, imported into any other python file.\n\n**Example changing or applying a setting:**\n\n```\nfrom .addon_updater import Updater as updater\nupdater.addon = \"addon_name\"\n```\n\n*Required settings*\n\n- **current_version:** The current version of the installed addon, typically acquired from bl_info\n  - Type: Tuple, e.g. (1,1,0) or (1,1) or bl_info[\"version\"]\n- **repo:** The name of the repository as found in the GitHub link\n  - Type: String, e.g. \"blender-addon-updater\"\n  - Note: Make sure to use the correct repo name based on the api engine used; {repo_name} is found in the following places:\n    - GitHub: Retrieved from the url of the repository link. Example: https://github.com/cgcookie/{repo_name}\n    - Bitbucket: Retrieved from the url of the repository link. Example: https://bitbucket.org/cgcookie/{repo_name}\n    - GitLab: You must go to the repository settings page, and use the *project ID* provided; note that this is a (string-formated) number, not a readable name. Example url where found: https://gitlab.com/TheDuckCow/test-updater-gitlab/edit, only visible to owner/editors.\n- **user:** The name of the user the repository belongs to\n  - Type: String, e.g. \"cgcookie\"\n  - Note: Required but not actually used with GitLab engine enabled\n\n*Optional settings*\n\n- **engine:**\n  - Type: String, one of: [\"github\",\"gitlab\",\"bitbucket\"], not case sensitive\n  - Default: \"github\"\n  - This selection sets the api back end for retrieving the code. This must be set to match the appropriate online repository where releases/tags are hosted\n- **private_token:**\n  - Type: String\n  - Default: None\n  - Currently only supports private tokens for GitLab. Used only for granting access to private repositories for updating.\n  - WARNING: Before providing or using a personal token, [PLEASE READ SECURITY COCNERN SECTION BELOW](https://github.com/CGCookie/blender-addon-updater/tree/dev#security-concerns-with-private-repositories)\n- **addon:**\n  - Type: String, e.g. \"demo_addon_updater\"\n  - Default: derived from the `__package__` global variable, but recommended to change to explicit string as `__package__` can differ based on how the user installs the addon\n  - Note this must be assigned once and at the very top of the UI file (addon_updater_ops.py) as the string is used in the bl_idname's for operator and panel registration.\n- **auto_reload_post_update:** If True, attempt to auto disable, refresh, and then re-enable the addon without needing to close blender\n  - Type: Bool, e.g. False\n  - Default: False\n  - Notes: Depending on the addon and class setup, it may still be necessary or more stable to restart blender to fully load. In some cases, this may lead to instability and thus it is advised to keep as false and accordingly inform the user to restart blender unless confident otherwise.\n    - If this is set to True, a common error is thinking that the update completed because the version number in the preferences panel appears to be updated, but it is very possible the actual python modules have not fully reloaded or restored to an initial startup state.\n    - If it is set to True, a popup will appear just before it tries to reload, and then immediately after it reloads to confirm it worked.\n- **fake_install:** Used for debugging, to simulate in the user interface installing an update without actually modifying any files\n  - Type: Bool, e.g. False\n  - Default: False\n  - Notes: Should be only used for debugging, and always set to false for production\n- **updater_path:** Path location of stored JSON state file, backups, and staging of installing a new version\n  - Type: String, absolute path location\n  - Default: \"{path to blender files}/addons/{addon name}/{addon name}_updater/\"\n- **verbose:** A debugging setting that prints additional information to the console\n  - Type: Bool, e.g. False\n  - Default: False\n  - Notes: Messages will still be printed if errors occur, but verbose is helpful to keep enabled while developing or debugging this code. It may even be worthwhile to expose this option to the user through a blender interface property\n- **website:** Website for this addon, specifically for manually downloading the addon\n  - Type: String, valid url\n  - Default: None\n  - Notes: Used for no purpose other than allowing a user to manually install an addon and its update. It should be very clear from this webpage where to get the download, and thus may not be a typical landing page.\n  - **backup_current** Create a backup of the current code when performing an update or reversion.\n- **overwrite_patterns:** A list of patterns to match for which files of the local addon install should be overwritten by matching files in the downloaded version version\n  - Type: List of strings, each item follows a match pattern supported by the python module fnmatch\n  - Default: `[]`, which is internally made equivalent to `[\"*.py\",\"*.pyc\"]`\n  - Notes: You can use wild card patterns, see documentation for fnmatch.filter. The new default behavior introduced here is setting `[\"*.py\",\"*.pyc\"]` means it matches the default behavior of blender. Also note this only describes patterns to allow *overwriting*, if a file in the new update doesn't already exist locally, then it will be installed to the local addon.\n  - Examples:\n    - `[\"some.py\"]` In this method, only files matching the name some.py would be overwritten via the update. Thus, even if the updated addon had a newer __init__.py file, it would not replace the local version. This method could be used to build a file replacement whitelist.\n    - `[\"*.json\"]` means all JSON files found in addon update will overwrite those of same name in current install. This would be useful if the addon only has configuration, read-only data that should be always updated with the addon. Note that default blender behavior would not overwrite such JSON files if already present in the local install, this gets around that\n    - `[\"*\"]` means that all matching files found in the update would overwrite files in the local install. Note this was the behavior pre updater v1.0.4, this is also the safest option to use if you want to ensure all files always get updated with the newer version in the update, including resource files. Be mindful that any local or custom modified files may get overwritten.\n    // also note that this is a new setting as of v1.0.4 of the updater; the previous behavior of the updater was using the equivalent setting of `[\"*\"]` which would mean that all files found in the update would overwrite files in the local install.\n    - `[]` or `[\"*.py\",\"*.pyc\"]` matches default blender behavior, ie same effect if user installs update manually through blender interface without deleting the existing addon first\n- **remove_pre_update_patterns:** A list of patterns to match for which files of the currently installed addon should be removed prior to running the update\n  - Type: List of strings, each item follows a match pattern supported by the python module fnmatch\n  - Default: `[]`, recommended/as configured in demo addon: [\"*.pyc\"]\n  - Notes: This explicitly will delete all files in the local addon install which match any of the rules, and will run after a backup is taken (so the backup is complete), but before the overwrite_patterns are applied. If the structure or files of an addon may change in the future, it may be wise to set remove_pre_update_patterns to [\"*.py\",\"*.pyc\"] which would ensure all python files are always removed prior to the update, thus ensuring no longer used files aren't present. Using it in this fashion would also negate the need to specify the same patterns in the overwrite_patterns option. Note this option only deletes files, not folders.\n  - Examples:\n    - `[\"*\"]` means all files in the addon (except those under the dedicated updater subfolder of the addon) will always be deleted prior to running the update. This is nearly equivalent to using clean=True in the run_update method (however that will also delete folders)\n    -  `[\"*.pyc\"]` means pycache files are always removed prior to update, which is a safe\n- **backup_ignore_patterns:** A setting to ignore certain files or folders when performing a backup prior to installing an update/target version, useful to avoid copying resources or large files that wouldn't be replaced by the update anyways (via not being included in the overwrite_patterns setting)\n  - Type: List of strings\n  - Default: None\n  - Notes: You can use wild card patterns, see documentation for shutil.copytree `ignore` input parameter as this is where the list is passed into. This is similar but slightly different to the patterns used in overwrite_patterns and remove_pre_update_patterns, except these will also apply to folders\n- **manual_only:** A setting which will permit only manual installs and not one-click updates\n  - Type: Bool, e.g. False\n  - Default: False\n  - Notes: This is useful if you always want to direct the user to a specific download page, but still want them to receive update notifications.\n- **showpopups:** A setting which when enabled will allow for popup notifications for new updates\n  - Type: Bool, e.g. False\n  - Default: True\n  - Notes: This setting was introduced in v1.0.5, where previous functionality was equivalent to the setting being equal to True. Note that popups will only work if the proper configuration is provided to trigger them, ie triggering a background check for update in the appropriate location.\n- **version_min_update:** A setting which sets the minimum allowable version to target installing, so that any earlier numbered releases will not appear in the target install dropdown or appear as notifications for updating\n  - Type: Tuple e.g. (1,2) or (1,2,3), should match the number of separators in bl_info\n  - Default: None\n  - Notes:\n    - This behaves as an \"equal to or greater\", example: if `version_min_update` is set to (1,1,1), then (1,1,1) and (1,1,2) are valid targets, but (1,1,0) would not be listed as an available install target.\n    - This also impacts what is considered as an update. Example: if the current addon version locally is v1.5 with `version_min_update` set to be (1,8), the addon will not perceive v1.6 as an update and thus would not notify the user.\n    - The most logical use for this setting is to assign the earliest addon version with a functional updater, so that users cannot downgrade to a version before there was an updater and thus not be able to easily revert back.\n- **version_max_update:** A setting which sets the maximum allowable version to target installing, so the target version and any higher numbered releases will not appear in the target install dropdown or appear as notifications for updating\n  - Type: Tuple e.g. (1,2) or (1,2,3), should match the number of separators in bl_info\n  - Default: None\n  - Notes:\n    - This behaves as an \"equal to or greater\". Example: if `version_max_update` is set to (1,1,1), then (1,1,1) and (1,1,2) will be ignored targets (won't appear in target install dropdowns and won't trigger update notifications), but (1,1,0) would still be recognized as an available target and trigger update notifications.\n     - This also impacts what is considered as an update. Example: if the current addon version locally is v1.5 with `version_max_update` set to be (1,6), the addon will not perceive v1.6 or v1.7 online as an update and thus would not notify the user.\n- **skip_tag:** A setting which defines how to pre-process tag names\n  - Type: Function, see example method `skip_tag_function` in the Operator File\n  - Default: `skip_tag_function` defined in `addon_updater_ops.py`\n  - Notes: This is where the `version_min_update` and `version_max_update` settings are utilized. Additionally, the source function `skip_tag_function` could be modified e.g. to parse out any tags including the text \"dev\" or similar such rules to limit what is counted as an available update and also what is listed in the target install dropdown.\n- **subfolder_path:** Define the root location of the `__init__.py` file in the repository\n  - Type: String\n  - Default: \"\", meaning the root repository folder\n  - Notes: Not required if your `__init__.py` file is in the root level of the addon. Otherwise, use this setting to indicate where it is located so the updater knows which folder to take updated files from\n- **use_releases:** (GitHub only) Choose to pull updates from releases only instead of tags, and use release names instead of tag numbers in target-install dropdowns\n  - Type: Bool\n  - Default: False\n  - Notes: If true, any tags that are not \"annotated\" (ie have release notes or attachments) will be filtered out, as tags are not necessarily releases. Additional note: if set to false, cannot pull release notes for GitHub repository (whereas BitBucket and GitLab do have release notes available via tags). This means that if in the future in-line release notes are included in the UI, this setting will need to be set to True in order to show release logs (not yet implemented as of v1.0.5)\n\n*User preference defined (ie optional but good to expose to user)*\n\n- **check_interval_enable:** Allow for background checking.\n- **check_interval_minutes:** Set the interval of minutes between the previous check for update and the next\n- **check_interval_hours:** Set the interval of hours between the previous check for update and the next\n- **check_interval_days:** Set the interval of days between the previous check for update and the next\n- **check_interval_months:** Set the interval of months between the previous check for update and the next\n\n*Internal values (read only by the Python Module)*\n\n- **addon_package:** The package name of the addon, used for enabling or disabling the addon\n  - Type: String\n  - Default: `__package__`\n  - Must use the provided default value of `__package__` , automatically assigned\n- **addon_root:** The location of the root of the updater file\n  - Type: String, path\n  - Default: `os.path.dirname(__file__)`\n- **async_checking:** If a background thread is currently active checking for an update, this flag is set to True and prevents additional checks for updates. Otherwise, it is set to false\n  - Type: Bool\n  - Default: False\n  - Notes:\n    - This may be used as a flag for conditional drawing, e.g. to draw a \"checking for update\" button while checking in the background\n    - However, even if the user were to still press a \"check for update\" button, the module would still prevent an additional thread being created until the existing one finishes by checking against this internal boolean\n- **json:** Contains important state information about the updater\n  - Type: Dictionary with string keys\n  - Default: {}\n  - Notes: This is used by both the module and the operator file to store saved state information, such as when the last update is and caching update links / versions to prevent the need to check the internet more than necessary. The contents of this dictionary object are directly saved to a JSON file in the addon updater folder. The contents are periodically updated, such as to save timestamps after checking for update, or saving locally the update link of not updated immediately, or storing the \"ignore update\" decision by user.\n- **source_zip:** Once a version of the addon is downloaded directly from the server, this variable is set to the absolute path to the zip file created.\n  - Type: String, OS path\n  - Default: None\n  - Notes: Path to the zip file named source.zip already downloaded\n- **tag_latest** Returns the most recent tag or version of the addon online\n  - Type: String, URL\n  - Default: None\n- **tag_names** Returns a list of the names (versions) for each tag of the addon online\n  - Type: list\n  - Default: []\n  - Note: this is analogous to reading tags from outside the Python Module.\n- **tags:** Contains a list of the tags (version numbers) of the addon\n  - Type: list\n  - Default: []\n  - Notes: Can be used if the user wants to download and install a version other than the most recent. Can be used to draw a dropdown of the available versions.\n- **update_link:** After check for update has completed and a version is found, this will be set to the direct download link of the new code zip file.\n- **update_ready:** Indicates if an update is ready\n  - Type: Bool\n  - Default: None\n  - Notes:\n    - Set to be True if a tag of a higher version number is found after checking for updates\n    - Set to be False if a tag of a higher version number is not found after checking for updates\n    - Set to be None before a check has been performed or cached\n    - Using `updater.update_ready == None` is a good check for use in draw functions, e.g. to show different options if an update is ready or not or needs to be checked for still\n- **update_version:** The version of the update downloaded or targeted\n  - Type: String\n  - Default: None\n  - Notes: This is set to the new addon version string, e.g. `(1,0,1)` and is used to compare against the installed addon version\n- **error:** If an error occurs, such as no internet or if the repo has no tags, this will be a string with the name of the error; otherwise, it is `None`\n  - Type: String\n  - Default: None\n  - It may be useful for user interfaces to check e.g. `updater.error != None` to draw a label with an error message e.g. `layout.label(updater.error_msg)`\n- **error_msg:** If an error occurs, such as no internet or if the repo has no tags, this will be a string with the description of the error; otherwise, it is `None`\n  - Type: String\n  - Default: None\n  - It may be useful for user interfaces to check e.g. `updater.error != None` to draw a label with an error message e.g. `layout.label(updater.error_msg)`\n\n\n\n# About addon_updater_ops\n\nThis is the code which acts as a bridge between the pure python addon_updater.py module and blender itself. It is safe and even advised to modify the Operator File to fit the UI/UX wishes. You should not need to modify the addon_updater.py file to make a customized updater experience.\n\n### User preferences UI\n\n![Alt](/images/updater_preferences.png)\n\nMost of the key settings for the user are available in the user preferences of the addon, including the ability to restore the addon, force check for an update now, and allowing the user to immediately check for an update (still runs in the background)\n\n![Alt](/images/condensed_ui.png)\n\nThis is an alternate, more condensed preferences UI example which removes more granular options such as settings for the intervals between update checks, restoring from backups, and targeting versions to install\n\n### Integrated panel UI\n\n![Alt](/images/integrated_panel.png)\n\n*If a check has been performed and an update is ready, this panel is displayed in the panel otherwise just dedicated to the addon's tools itself. The draw function can be appended to any panel.*\n\n### Popup notice after new update found\n\n![Alt](/images/popup_update.png)\n\n*After a check for update has occurred, either by the user interface or automatically in the background (with auto-check enabled and the interval passed), a popup is set to appear when the draw panel is first triggered. It will not re-trigger until blender is restarted. Pressing ignore on the integrate panel UI box will prevent popups in the future.*\n\n\n### Install different addon versions\n\n![Alt](/images/install_versions.png)\n\n*In addition to grabbing the code for the most recent release or tag of a GitHub repository, this updater can also install other target versions of the addon through the popup interface.*\n\n\n### If your repository doesn't have any releases...\n\n![Alt](/images/no_releases.png)\n\n*This is what you will find. See below on creating tags and releases*\n\n\n# How to use git and tags/releases\n\n## What are they\n\nFrom a [good reference website](https://git-scm.com/book/en/v2/Git-Basics-Tagging), a tag acts much like a branch except it never changes - it is linked with a specific commit in time. Tags can be annotated to have information like release logs or binaries, but at the base they allow one to designate major versions of code. This addon updater uses tag names in order to base the comparison version numbers, and thus to also grab the code from those points in times.\n\n## Through the interface (GitHub specific)\n\nView the releases tab at the top of any GitHub repository to create and view all releases and tags. Note that a release is just an annotated tag, and that this repository will function with both tags and releases.\n\n## Through command line (for any git-based system)\n\nTo show all tags on your local git repository use `git tag`\n\nTo create a new tag with the current local or pushed commit, use e.g. `git tag -a v0.0.1 -m \"v0.0.1 release\"` which will create an annotated tag.\n\nTo push this tag up to the server (which won't happen automatically via `git push`), use `git push origin v0.0.1` or whichever according tag name\n\n# Configuring what files are removed, overwritten, or left alone during update\n\nSince v1.0.4 of the updater module, logic exists to help control what is modified or left in place during the updating process. This is done through the overwrite_patterns and remove_pre_update_patterns settings detailed above. Below are the common scenarios or use cases\n\n**I don't understand this feature and I just want to use the default configuration which matches blender's install behavior**\n\nFair enough, in that case use the following settings - or just remove the lines entirely from the Operator File as these are the default values assigned to the updater class object.\n\n```\n# only overwrite matching python files found in the update, files like .txt or .blend will not be overwritten even if newer versions are in the update\nupdater.overwrite_patterns = [\"*.py\",\"*.pyc\"]\n# don't delete any files preemptively\nupdater.remove_pre_update_patterns = [ ]\n```\n\nIf you wanted to instead match the default behavior of the addon updater pre v1.0.4, then use the following\n```\n# overwrite any file found in the local install which has a corresponding file in the update\nupdater.overwrite_patterns = [\"*\"]\n# don't delete any files files preemptively\nupdater.remove_pre_update_patterns = [ ]\n```\n\n**I want to shoot myself in the foot and make updating not work at all**\n\nOr in other words... *don't* use the following setup, as it effectively prevents the updater from updating anything at all!\n\n```\n# don't overwrite any files matching the local install in the update\nupdater.overwrite_patterns = [ ]\n# don't delete any files files preemptively\nupdater.remove_pre_update_patterns = [ ]\n```\n\nThis would still add in *new* files present in the update not present in the local install. For this reason, this actually may be a valid setup if used in conjunction with clean_install set to True, which simulates a fresh install. When clean_install = True, these patterns are effectively rendered pointless, so it's still better to not define them in the way above.\n\n\n**Addon contains only py files, no resources (e.g. JSON files, images, blends), and against better judgment, not even licenses or readme files**\n\nIn this example, we only need to worry about replacing the python files with the new python files. By default, this demo addon is configured so that new py files and pyc files will overwrite old files with matching paths/names in the local install. This is accomplished by setting `updater.overwrite_patterns = [\"*.py\",\"*.pyc\"]` in the operator file. You could also be more explicit and specify all files which may be overwritten via `updater.overwrite_patterns = [\"__init__.py\", \"module.py\", \"*.pyc\"]` for example (noting the \"\\*.pyc\" is still there to ensure all caches are flushed).\n\nNote that if in the future, a file is renamed e.g. from module.py to new_module.py, when the update runs (and assuming `remove_pre_update_patterns` has been left to it's empty list default), then the updater will copy in the new_module.py into the local install, while also leaving the previous version's module.py in place. The result will have both the module.py and new_module.py file in place.\n\nIf you wanted to future proof your updater to ensure no old python files are left around due to a changes in structure or filenames, it would be safe to instead set `updater.remove_pre_update_patterns = [\"*.py\",\"*.pyc\"]` meaning all python files and cached files will always be removed prior to updating. After the update completes, the only python files that will be present are those that came directly from the update itself.\n\nWhile you could also use `updater.remove_pre_update_patterns = [\"*\"]`, it is not recommended unless absolutely necessary. You never know when a user may try to place files in the addon subfolder, or if sometime down in the future you might want the updater to not clear everything out, so it's best to only explicitly delete the minimum which is needed, and be sure to plan ahead.\n\n**Addon contains py files and resource files, but no user/local configuration files**\n\nThis is the more common use case. It is similar to the above, except now there are also additional files such as the readme.md, the license.txt, and perhaps a blend file with some models or other resources.\n\nIf the user were to install the update manually through the blender UI with an older version of the addon in place, it would actually only overwrite the py files. The readme.md and licenses.txt that existed previously would not change, they would not be overwritten. However, any new files in the update not in the local install (such as a new blend file) will be moved into the local install folder. If a blend file is in the local install prior to updating but is not found in the new addon update, it would still be left in place. Essentially, blender's default behavior is to only overwrite and update python files, and when copying in new resources it favors the files already present in the local install.\n\nInstead of this default behavior, the following settings would be more appropriate for the situation of readme's and asset blends, since they may change between versions.\n\n```\nupdater.overwrite_patterns = [\"README.md\", \"*.blend\"]\n```\n\nIn this setup, the updater is told to always replace the readme file explicitly (note the case sensitivity). No other files are indicated to be overwritten, indicating for example the license file will never be overwritten with an update - that shouldn't be changing anyways. This setup would actually mean not even the python files are overwritten if the update has matching files to the local install. Not even the __init__.py file would be updated, which is where the next setting becomes useful.\n\nThe \"\\*.blend\" will result in any blend file being overwritten if matching locally to the update. e.g. /addonroot/assets/resources.blend will be replaced with the e.g. /addonroot/assets/resources.blend found in update repository. This would make sense if the blend file is static and not expected to be ever user modified.\n\n```\nupdater.remove_pre_update_patterns = [\"*.py\",\"*.pyc\"]\n```\n\nThe second line tells the updater to delete all .py and .pyc files prior to updating, no matter what. This why we don't need to also add \\*.py into the `overwrite_patterns`, because if the python files have already been removed, then there's no chance for the update to have a matching python file in the local install (and thus no need to check against overwriting rules). This setup also has the benefit of never leaving old, unused python code around. if module_new.py is used in one version but then removed in the next, this setup of pre-removing all py files ensures it is deleted. Note that this doesn't do anything to any other files. Meaning existing files such as blends, images, JSON etc will all be left alone. With the exception of blend files (as per `overwrite_patterns` above), they also won't be overwritten - even if there are updates.\n\n**Addon contains py files, resource files, and user/local configuration files**\n\nThis is the most intricate setup, but layers on more useful behavior even in unique situations.\n\nImagine an addon has a changing python code structure, assets which should be updated with each update, but also configuration files with default settings provided in the master repository, but local changes wanted to be kept. Furthermore, the user may install custom image textures saved in the addon folder so you will not know the names ahead of time, but you also want to ensure custom icon file updates can be made.\n\n```\n# example addon setup\n__init__.py\nmodule.py\nicons/custom_icon.png\nimages/   # folder where custom png images will be installed\nREADME.md\nassets/default.blend\nassets/customizable.blend\n\n```\n\nTo accomplish the mentioned behavior, use the below configuration.\n\n```\nupdater.overwrite_patterns = [\"README.md\", \"custom_icon.png\"]\nupdater.remove_pre_update_patterns = [\"*.py\", \"*.pyc\", \"default.blend\"]\n```\n\nBreaking this down, we always specify to overwrite the README and custom_icon.png files explicitly. No need to remove either in pre update since we expect they will be found in the update, and the overwrite patterns ensures they always get overwritten and only those files.\n\nThen, we specify to delete all python files before running the update, to ensure the only python files are part of the latest release. We also force delete the file matching the name *default.blend.* If this was added as an overwrite pattern instead and the default.blend file name were ever renamed in the master repository, the updater would not end up removing this extra asset. And so we delete it directly, and presume the update will contain the appropriately named and updated blend file.\n\nJust as importantly, note how the customizable.blend is not mentioned in either line. This means that there are no rules which would allow for this file to be overwritten or removed. This is desired since the user could have modified this file per their own needs, and we don't want to reset it. If the file was manually removed by the user or otherwise not present in a previous version of the addon, the update would still copy it over as found in the master repository.\n\n\n**In conclusion**\n\nIf you are planning to modify the `overwrite_patterns` or `remove_pre_update_patterns` settings, be sure to plan and test it works as you expect. It's important to have \"\\*.py\" in at least one of them, or alternatively individually name all python file basenames in either of the two settings.\n\nIt is redundant to have the same rule in both settings, behavior of the `remove_pre_update_patterns` will supersede the more passive overwriting permission rules of `overwrite_patterns`\n\nThe pattern matching is done on an \"or\" basis, meaning in the set [\"*.py\", \"module.py\"], the second list item is redundant as the \"*.py\" already\n\nThe patterns only match to filenames, so there is no use in including in paths like assets/icon.png or directory names.\n\nFinally, enabled verbose and check the console output after running an update! There are explicit printouts for when any files is \"pre-removed\", overwritten, or ignored for overwriting due to not matching a pattern. Use this to debug.\n\n\n# Blender 2.7 and 2.8\n\nThis repository and example addon has been updated to still work for Blender 2.7x, 2.8x, 2.9x, and (as of writing) early builds of 3.0. Optionally, addon developers could still choose to host dedicated 2.8x versions separate from 2.7x versions while using this updater system. Note that annotations are applied to class fields programmatically instead of through coding syntax (e.g. you will not see `propname: bpy.props...`, but the same effect will be in place and there should be no console warnings)\n\nNote that, as an addon developer, you have different options for supporting Blender 2.7 and 2.8+ while still using this updater system. These are:\n\n1) Make the addon work for 2.7x and 2.8+ simultaneously (in the same way that this module and demo addon does).\n    - This requires some extra work, in particular note the workaround of annotations as accomplished by the `make_annotations` function.\n2) Have dedicated, separate releases for Blender 2.7x and 2.8+ which are separated by a major version, and use min/max conversioning to isolate which users can update to which versions.\n    - For instance, if an existing addon is version 1.5 and works on blender 2.79, then a feature-parity version for Blender 2.8 could be released as addon version 2.0; this 2.0 addon with have a `version_min_update` set to be 2.0 for the blender 2.8 code, and the Blender 2.7x code would set `version_max_update` to be 2.0 as well as a ceiling.\n    - The next update to the Blender 2.79-compatible addon (released at the same time or earlier, to prevent 2.7x users from accidentally updating to breaking 2.8 code) should push this settings change to make sure users don't accidentally update to a version they shouldn't.\n    - Note in this scenario, you also prevent being able to update Blender 2.7x version numbers to or beyond 2.0. Note that there is no obligation to simultaneously update the Blender 2.7x and 2.8x versions at the same time as the version numbers themselves are not actually linked in any way.\n    - The 2.7x and 2.8x code would be kept in different branches, and tags would be made targeting those different branches accordingly. Given Blender 2.8x will be the long term future, it may make most sense to dedicate the master branch to be 2.8 and create a 2.7x branch for parallel legacy support, but the choice doesn't really matter as a tag is treated the same regardless of the source branch.\n3) Parallel version releases with build attachments for each new version.\n    - This method is in one way simple as the same version numbers would work for both Blender 2.7x and 2.8x code, while still having separate code in different branches so you don't have to make code (such as annotation syntax) compatible for both at the same time in the same files. You could even have everything in the same branch with just duplicate files (e.g. a ui.py and ui_28.py).\n    - The crux of this method is that instead of the updater pulling down the raw code associated with the tag/release, it uses release attachments instead. You would need to build\n    - This does require releasing the 2.7x and 2.8 code at the same time\n    - Extra logic will need to be programmed in the `addon_updater_ops.py: select_link_function` function to parse for the correct attachment given the running version of blender (instead of just the first release attachment, the default behavior), as well as enabling the `use_releases` setting in the ops file\n    - For reference, this is essentially the method developers use to maintain and distribute updates for operating-specific builds of addons\n\n\n# Security concerns with private repositories\n\nSupport for private repositories is still a work in progress for Bitbucket and GitHub, while already available for GitLab. At this time, they are only supported via authentication through personal or private tokens. These are assigned to an individual user and while can be restricted what access they do or don't have, they can **effectively act as an alternate to a password.** While this updater module is configured to only *read/download* code, a private token would allow both read and write capabilities to anyone who knows how to use the according api. By nature of python modules, this private token is easily read in source code or can be reverse compiled in pyc code and used for malicious or unintended purposes.\n\nFor this reason, it is very important to be aware and setup tokens accordingly. As the authentication implementation advances here, the recommendations may change but in the meantime:\n- GitLab: Supported through Personal Tokens\n  - Tokens are not needed and should not be used for public repositories\n  - Personal access tokens can be [viewed and created here](https://gitlab.com/profile/personal_access_tokens)\n  - Consider whether to provide an expiration date. Once expired any existing installs using the token will no longer successfully pull updates from private repositories. Therefore, if a user has the updater-enabled addon installed but leverages an expired token, they will not be able to update.\n  - Tokens should be enabled for api *read access* only, to limit (mis) uses.\n  - This token is *user* specific, *not* repository specific; therefore, anyone with the token is able to read anything via the GitLab api to any repository this user has access to. **For this reason,** it is very important to **NOT USE YOUR PERSONAL ACCOUNT** to create a token. Rather, you are better suited to create a secondary \"machine user\" account which is used only for the purpose of api access. This 'user' should be assigned to the project as a \"reporter\" for minimum required capabilities.\n  - Use at own risk and ensure to do according research to ensure there are no security risks or possible backlashes due to providing updating for private repositories on GitLab.\n  - When in doubt, you can always revoke a personal token - but once revoked, it cannot be re-enabled and thus any existing installs using the token will no longer be able to pull from the private repo unless manually updating the addon themselves.\n  - These are only recommendations. As indicated by the GPL license, software is provided as-is and developers are not held liable to mishandling which results in unwanted consequences such as malicious exploit of a badly implemented private repository updating.\n- GitHub: Not yet supported. Likely to only be included via community contribution.\n- Bitbucket: Not yet supported. Likely to only be included via community contribution.\n\n# Issues or help\n\nIf you are attempting to integrate this code into your addon and run into problems, [please open a new issue](https://github.com/CGCookie/blender-addon-updater/issues). As the module improves, it will be easier for more developers to integrate updating and improve blender's user experience overall!\n\nPlease note that the updater code is built to be dependent on existing api's of the mentioned major source code repository sites. As these api's may be subject to change or interruption, updating capabilities may be impacted for existing users.\n"
  },
  {
    "path": "__init__.py",
    "content": "# ##### BEGIN GPL LICENSE BLOCK #####\n#\n#  This program is free software; you can redistribute it and/or\n#  modify it under the terms of the GNU General Public License\n#  as published by the Free Software Foundation; either version 2\n#  of the License, or (at your option) any later version.\n#\n#  This program is distributed in the hope that it will be useful,\n#  but WITHOUT ANY WARRANTY; without even the implied warranty of\n#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#  GNU General Public License for more details.\n#\n#  You should have received a copy of the GNU General Public License\n#  along with this program; if not, write to the Free Software Foundation,\n#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\nbl_info = {\n\t\"name\": \"Addon Updater Demo\",\n\t\"description\": \"Demo addon for showcasing the blender-addon-updater module\",\n\t\"author\": \"Patrick W. Crawford, neomonkeus\",\n\t\"version\": (1, 1, 1),\n\t\"blender\": (2, 80, 0),\n\t\"location\": \"View 3D > Tool Shelf > Demo Updater\",\n\t\"warning\": \"\",\n\t\"wiki_url\": \"https://github.com/CGCookie/blender-addon-updater\",\n\t\"tracker_url\": \"https://github.com/CGCookie/blender-addon-updater/issues\",\n\t\"category\": \"System\"\n}\n\n\nimport bpy\n\n# Updater ops import, all setup in this file.\nfrom . import addon_updater_ops\n\n\nclass DemoUpdaterPanel(bpy.types.Panel):\n\t\"\"\"Panel to demo popup notice and ignoring functionality\"\"\"\n\tbl_label = \"Updater Demo Panel\"\n\tbl_idname = \"OBJECT_PT_DemoUpdaterPanel_hello\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'TOOLS' if bpy.app.version < (2, 80) else 'UI'\n\tbl_context = \"objectmode\"\n\tbl_category = \"Tools\"\n\n\tdef draw(self, context):\n\t\tlayout = self.layout\n\n\t\t# Call to check for update in background.\n\t\t# Note: built-in checks ensure it runs at most once, and will run in\n\t\t# the background thread, not blocking or hanging blender.\n\t\t# Internally also checks to see if auto-check enabled and if the time\n\t\t# interval has passed.\n\t\taddon_updater_ops.check_for_update_background()\n\n\t\tlayout.label(text=\"Demo Updater Addon\")\n\t\tlayout.label(text=\"\")\n\n\t\tcol = layout.column()\n\t\tcol.scale_y = 0.7\n\t\tcol.label(text=\"If an update is ready,\")\n\t\tcol.label(text=\"popup triggered by opening\")\n\t\tcol.label(text=\"this panel, plus a box ui\")\n\n\t\t# Could also use your own custom drawing based on shared variables.\n\t\tif addon_updater_ops.updater.update_ready:\n\t\t\tlayout.label(text=\"Custom update message\", icon=\"INFO\")\n\t\tlayout.label(text=\"\")\n\n\t\t# Call built-in function with draw code/checks.\n\t\taddon_updater_ops.update_notice_box_ui(self, context)\n\n\n@addon_updater_ops.make_annotations\nclass DemoPreferences(bpy.types.AddonPreferences):\n\t\"\"\"Demo bare-bones preferences\"\"\"\n\tbl_idname = __package__\n\n\t# Addon updater preferences.\n\n\tauto_check_update = bpy.props.BoolProperty(\n\t\tname=\"Auto-check for Update\",\n\t\tdescription=\"If enabled, auto-check for updates using an interval\",\n\t\tdefault=False)\n\n\tupdater_interval_months = bpy.props.IntProperty(\n\t\tname='Months',\n\t\tdescription=\"Number of months between checking for updates\",\n\t\tdefault=0,\n\t\tmin=0)\n\n\tupdater_interval_days = bpy.props.IntProperty(\n\t\tname='Days',\n\t\tdescription=\"Number of days between checking for updates\",\n\t\tdefault=7,\n\t\tmin=0,\n\t\tmax=31)\n\n\tupdater_interval_hours = bpy.props.IntProperty(\n\t\tname='Hours',\n\t\tdescription=\"Number of hours between checking for updates\",\n\t\tdefault=0,\n\t\tmin=0,\n\t\tmax=23)\n\n\tupdater_interval_minutes = bpy.props.IntProperty(\n\t\tname='Minutes',\n\t\tdescription=\"Number of minutes between checking for updates\",\n\t\tdefault=0,\n\t\tmin=0,\n\t\tmax=59)\n\n\tdef draw(self, context):\n\t\tlayout = self.layout\n\n\t\t# Works best if a column, or even just self.layout.\n\t\tmainrow = layout.row()\n\t\tcol = mainrow.column()\n\n\t\t# Updater draw function, could also pass in col as third arg.\n\t\taddon_updater_ops.update_settings_ui(self, context)\n\n\t\t# Alternate draw function, which is more condensed and can be\n\t\t# placed within an existing draw function. Only contains:\n\t\t#   1) check for update/update now buttons\n\t\t#   2) toggle for auto-check (interval will be equal to what is set above)\n\t\t# addon_updater_ops.update_settings_ui_condensed(self, context, col)\n\n\t\t# Adding another column to help show the above condensed ui as one column\n\t\t# col = mainrow.column()\n\t\t# col.scale_y = 2\n\t\t# ops = col.operator(\"wm.url_open\",\"Open webpage \")\n\t\t# ops.url=addon_updater_ops.updater.website\n\n\nclasses = (\n\tDemoPreferences,\n\tDemoUpdaterPanel\n)\n\n\ndef register():\n\t# Addon updater code and configurations.\n\t# In case of a broken version, try to register the updater first so that\n\t# users can revert back to a working version.\n\taddon_updater_ops.register(bl_info)\n\n\t# Register the example panel, to show updater buttons.\n\tfor cls in classes:\n\t\taddon_updater_ops.make_annotations(cls)  # Avoid blender 2.8 warnings.\n\t\tbpy.utils.register_class(cls)\n\n\ndef unregister():\n\t# Addon updater unregister.\n\taddon_updater_ops.unregister()\n\tfor cls in reversed(classes):\n\t\tbpy.utils.unregister_class(cls)\n"
  },
  {
    "path": "addon_updater.py",
    "content": "# ##### BEGIN GPL LICENSE BLOCK #####\n#\n#  This program is free software; you can redistribute it and/or\n#  modify it under the terms of the GNU General Public License\n#  as published by the Free Software Foundation; either version 2\n#  of the License, or (at your option) any later version.\n#\n#  This program is distributed in the hope that it will be useful,\n#  but WITHOUT ANY WARRANTY; without even the implied warranty of\n#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#  GNU General Public License for more details.\n#\n#  You should have received a copy of the GNU General Public License\n#  along with this program; if not, write to the Free Software Foundation,\n#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n\n\"\"\"\nSee documentation for usage\nhttps://github.com/CGCookie/blender-addon-updater\n\"\"\"\n\n__version__ = \"1.1.1\"\n\nimport errno\nimport traceback\nimport platform\nimport ssl\nimport urllib.request\nimport urllib\nimport os\nimport json\nimport zipfile\nimport shutil\nimport threading\nimport fnmatch\nfrom datetime import datetime, timedelta\n\n# Blender imports, used in limited cases.\nimport bpy\nimport addon_utils\n\n# -----------------------------------------------------------------------------\n# The main class\n# -----------------------------------------------------------------------------\n\n\nclass SingletonUpdater:\n    \"\"\"Addon updater service class.\n\n    This is the singleton class to instance once and then reference where\n    needed throughout the addon. It implements all the interfaces for running\n    updates.\n    \"\"\"\n    def __init__(self):\n\n        self._engine = GithubEngine()\n        self._user = None\n        self._repo = None\n        self._website = None\n        self._current_version = None\n        self._subfolder_path = None\n        self._tags = list()\n        self._tag_latest = None\n        self._tag_names = list()\n        self._latest_release = None\n        self._use_releases = False\n        self._include_branches = False\n        self._include_branch_list = ['master']\n        self._include_branch_auto_check = False\n        self._manual_only = False\n        self._version_min_update = None\n        self._version_max_update = None\n\n        # By default, backup current addon on update/target install.\n        self._backup_current = True\n        self._backup_ignore_patterns = None\n\n        # Set patterns the files to overwrite during an update.\n        self._overwrite_patterns = [\"*.py\", \"*.pyc\"]\n        self._remove_pre_update_patterns = list()\n\n        # By default, don't auto disable+re-enable the addon after an update,\n        # as this is less stable/often won't fully reload all modules anyways.\n        self._auto_reload_post_update = False\n\n        # Settings for the frequency of automated background checks.\n        self._check_interval_enabled = False\n        self._check_interval_months = 0\n        self._check_interval_days = 7\n        self._check_interval_hours = 0\n        self._check_interval_minutes = 0\n\n        # runtime variables, initial conditions\n        self._verbose = False\n        self._use_print_traces = True\n        self._fake_install = False\n        self._async_checking = False  # only true when async daemon started\n        self._update_ready = None\n        self._update_link = None\n        self._update_version = None\n        self._source_zip = None\n        self._check_thread = None\n        self._select_link = None\n        self.skip_tag = None\n\n        # Get data from the running blender module (addon).\n        self._addon = __package__.lower()\n        self._addon_package = __package__  # Must not change.\n        self._updater_path = os.path.join(\n            os.path.dirname(__file__), self._addon + \"_updater\")\n        self._addon_root = os.path.dirname(__file__)\n        self._json = dict()\n        self._error = None\n        self._error_msg = None\n        self._prefiltered_tag_count = 0\n\n        # UI properties, not used within this module but still useful to have.\n\n        # to verify a valid import, in place of placeholder import\n        self.show_popups = True  # UI uses to show popups or not.\n        self.invalid_updater = False\n\n        # pre-assign basic select-link function\n        def select_link_function(self, tag):\n            return tag[\"zipball_url\"]\n\n        self._select_link = select_link_function\n\n    def print_trace(self):\n        \"\"\"Print handled exception details when use_print_traces is set\"\"\"\n        if self._use_print_traces:\n            traceback.print_exc()\n\n    def print_verbose(self, msg):\n        \"\"\"Print out a verbose logging message if verbose is true.\"\"\"\n        if not self._verbose:\n            return\n        print(\"{} addon: \".format(self.addon) + msg)\n\n    # -------------------------------------------------------------------------\n    # Getters and setters\n    # -------------------------------------------------------------------------\n    @property\n    def addon(self):\n        return self._addon\n\n    @addon.setter\n    def addon(self, value):\n        self._addon = str(value)\n\n    @property\n    def api_url(self):\n        return self._engine.api_url\n\n    @api_url.setter\n    def api_url(self, value):\n        if not self.check_is_url(value):\n            raise ValueError(\"Not a valid URL: \" + value)\n        self._engine.api_url = value\n\n    @property\n    def async_checking(self):\n        return self._async_checking\n\n    @property\n    def auto_reload_post_update(self):\n        return self._auto_reload_post_update\n\n    @auto_reload_post_update.setter\n    def auto_reload_post_update(self, value):\n        try:\n            self._auto_reload_post_update = bool(value)\n        except:\n            raise ValueError(\"auto_reload_post_update must be a boolean value\")\n\n    @property\n    def backup_current(self):\n        return self._backup_current\n\n    @backup_current.setter\n    def backup_current(self, value):\n        if value is None:\n            self._backup_current = False\n        else:\n            self._backup_current = value\n\n    @property\n    def backup_ignore_patterns(self):\n        return self._backup_ignore_patterns\n\n    @backup_ignore_patterns.setter\n    def backup_ignore_patterns(self, value):\n        if value is None:\n            self._backup_ignore_patterns = None\n        elif not isinstance(value, list):\n            raise ValueError(\"Backup pattern must be in list format\")\n        else:\n            self._backup_ignore_patterns = value\n\n    @property\n    def check_interval(self):\n        return (self._check_interval_enabled,\n                self._check_interval_months,\n                self._check_interval_days,\n                self._check_interval_hours,\n                self._check_interval_minutes)\n\n    @property\n    def current_version(self):\n        return self._current_version\n\n    @current_version.setter\n    def current_version(self, tuple_values):\n        if tuple_values is None:\n            self._current_version = None\n            return\n        elif type(tuple_values) is not tuple:\n            try:\n                tuple(tuple_values)\n            except:\n                raise ValueError(\n                    \"current_version must be a tuple of integers\")\n        for i in tuple_values:\n            if type(i) is not int:\n                raise ValueError(\n                    \"current_version must be a tuple of integers\")\n        self._current_version = tuple(tuple_values)\n\n    @property\n    def engine(self):\n        return self._engine.name\n\n    @engine.setter\n    def engine(self, value):\n        engine = value.lower()\n        if engine == \"github\":\n            self._engine = GithubEngine()\n        elif engine == \"gitlab\":\n            self._engine = GitlabEngine()\n        elif engine == \"bitbucket\":\n            self._engine = BitbucketEngine()\n        else:\n            raise ValueError(\"Invalid engine selection\")\n\n    @property\n    def error(self):\n        return self._error\n\n    @property\n    def error_msg(self):\n        return self._error_msg\n\n    @property\n    def fake_install(self):\n        return self._fake_install\n\n    @fake_install.setter\n    def fake_install(self, value):\n        if not isinstance(value, bool):\n            raise ValueError(\"fake_install must be a boolean value\")\n        self._fake_install = bool(value)\n\n    # not currently used\n    @property\n    def include_branch_auto_check(self):\n        return self._include_branch_auto_check\n\n    @include_branch_auto_check.setter\n    def include_branch_auto_check(self, value):\n        try:\n            self._include_branch_auto_check = bool(value)\n        except:\n            raise ValueError(\"include_branch_autocheck must be a boolean\")\n\n    @property\n    def include_branch_list(self):\n        return self._include_branch_list\n\n    @include_branch_list.setter\n    def include_branch_list(self, value):\n        try:\n            if value is None:\n                self._include_branch_list = ['master']\n            elif not isinstance(value, list) or len(value) == 0:\n                raise ValueError(\n                    \"include_branch_list should be a list of valid branches\")\n            else:\n                self._include_branch_list = value\n        except:\n            raise ValueError(\n                \"include_branch_list should be a list of valid branches\")\n\n    @property\n    def include_branches(self):\n        return self._include_branches\n\n    @include_branches.setter\n    def include_branches(self, value):\n        try:\n            self._include_branches = bool(value)\n        except:\n            raise ValueError(\"include_branches must be a boolean value\")\n\n    @property\n    def json(self):\n        if len(self._json) == 0:\n            self.set_updater_json()\n        return self._json\n\n    @property\n    def latest_release(self):\n        if self._latest_release is None:\n            return None\n        return self._latest_release\n\n    @property\n    def manual_only(self):\n        return self._manual_only\n\n    @manual_only.setter\n    def manual_only(self, value):\n        try:\n            self._manual_only = bool(value)\n        except:\n            raise ValueError(\"manual_only must be a boolean value\")\n\n    @property\n    def overwrite_patterns(self):\n        return self._overwrite_patterns\n\n    @overwrite_patterns.setter\n    def overwrite_patterns(self, value):\n        if value is None:\n            self._overwrite_patterns = [\"*.py\", \"*.pyc\"]\n        elif not isinstance(value, list):\n            raise ValueError(\"overwrite_patterns needs to be in a list format\")\n        else:\n            self._overwrite_patterns = value\n\n    @property\n    def private_token(self):\n        return self._engine.token\n\n    @private_token.setter\n    def private_token(self, value):\n        if value is None:\n            self._engine.token = None\n        else:\n            self._engine.token = str(value)\n\n    @property\n    def remove_pre_update_patterns(self):\n        return self._remove_pre_update_patterns\n\n    @remove_pre_update_patterns.setter\n    def remove_pre_update_patterns(self, value):\n        if value is None:\n            self._remove_pre_update_patterns = list()\n        elif not isinstance(value, list):\n            raise ValueError(\n                \"remove_pre_update_patterns needs to be in a list format\")\n        else:\n            self._remove_pre_update_patterns = value\n\n    @property\n    def repo(self):\n        return self._repo\n\n    @repo.setter\n    def repo(self, value):\n        try:\n            self._repo = str(value)\n        except:\n            raise ValueError(\"repo must be a string value\")\n\n    @property\n    def select_link(self):\n        return self._select_link\n\n    @select_link.setter\n    def select_link(self, value):\n        # ensure it is a function assignment, with signature:\n        # input self, tag; returns link name\n        if not hasattr(value, \"__call__\"):\n            raise ValueError(\"select_link must be a function\")\n        self._select_link = value\n\n    @property\n    def stage_path(self):\n        return self._updater_path\n\n    @stage_path.setter\n    def stage_path(self, value):\n        if value is None:\n            self.print_verbose(\"Aborting assigning stage_path, it's null\")\n            return\n        elif value is not None and not os.path.exists(value):\n            try:\n                os.makedirs(value)\n            except:\n                self.print_verbose(\"Error trying to staging path\")\n                self.print_trace()\n                return\n        self._updater_path = value\n\n    @property\n    def subfolder_path(self):\n        return self._subfolder_path\n\n    @subfolder_path.setter\n    def subfolder_path(self, value):\n        self._subfolder_path = value\n\n    @property\n    def tags(self):\n        if len(self._tags) == 0:\n            return list()\n        tag_names = list()\n        for tag in self._tags:\n            tag_names.append(tag[\"name\"])\n        return tag_names\n\n    @property\n    def tag_latest(self):\n        if self._tag_latest is None:\n            return None\n        return self._tag_latest[\"name\"]\n\n    @property\n    def update_link(self):\n        return self._update_link\n\n    @property\n    def update_ready(self):\n        return self._update_ready\n\n    @property\n    def update_version(self):\n        return self._update_version\n\n    @property\n    def use_releases(self):\n        return self._use_releases\n\n    @use_releases.setter\n    def use_releases(self, value):\n        try:\n            self._use_releases = bool(value)\n        except:\n            raise ValueError(\"use_releases must be a boolean value\")\n\n    @property\n    def user(self):\n        return self._user\n\n    @user.setter\n    def user(self, value):\n        try:\n            self._user = str(value)\n        except:\n            raise ValueError(\"User must be a string value\")\n\n    @property\n    def verbose(self):\n        return self._verbose\n\n    @verbose.setter\n    def verbose(self, value):\n        try:\n            self._verbose = bool(value)\n            self.print_verbose(\"Verbose is enabled\")\n        except:\n            raise ValueError(\"Verbose must be a boolean value\")\n\n    @property\n    def use_print_traces(self):\n        return self._use_print_traces\n\n    @use_print_traces.setter\n    def use_print_traces(self, value):\n        try:\n            self._use_print_traces = bool(value)\n        except:\n            raise ValueError(\"use_print_traces must be a boolean value\")\n\n    @property\n    def version_max_update(self):\n        return self._version_max_update\n\n    @version_max_update.setter\n    def version_max_update(self, value):\n        if value is None:\n            self._version_max_update = None\n            return\n        if not isinstance(value, tuple):\n            raise ValueError(\"Version maximum must be a tuple\")\n        for subvalue in value:\n            if type(subvalue) is not int:\n                raise ValueError(\"Version elements must be integers\")\n        self._version_max_update = value\n\n    @property\n    def version_min_update(self):\n        return self._version_min_update\n\n    @version_min_update.setter\n    def version_min_update(self, value):\n        if value is None:\n            self._version_min_update = None\n            return\n        if not isinstance(value, tuple):\n            raise ValueError(\"Version minimum must be a tuple\")\n        for subvalue in value:\n            if type(subvalue) != int:\n                raise ValueError(\"Version elements must be integers\")\n        self._version_min_update = value\n\n    @property\n    def website(self):\n        return self._website\n\n    @website.setter\n    def website(self, value):\n        if not self.check_is_url(value):\n            raise ValueError(\"Not a valid URL: \" + value)\n        self._website = value\n\n    # -------------------------------------------------------------------------\n    # Parameter validation related functions\n    # -------------------------------------------------------------------------\n    @staticmethod\n    def check_is_url(url):\n        if not (\"http://\" in url or \"https://\" in url):\n            return False\n        if \".\" not in url:\n            return False\n        return True\n\n    def _get_tag_names(self):\n        tag_names = list()\n        self.get_tags()\n        for tag in self._tags:\n            tag_names.append(tag[\"name\"])\n        return tag_names\n\n    def set_check_interval(self, enabled=False,\n                           months=0, days=14, hours=0, minutes=0):\n        \"\"\"Set the time interval between automated checks, and if enabled.\n\n        Has enabled = False as default to not check against frequency,\n        if enabled, default is 2 weeks.\n        \"\"\"\n\n        if type(enabled) is not bool:\n            raise ValueError(\"Enable must be a boolean value\")\n        if type(months) is not int:\n            raise ValueError(\"Months must be an integer value\")\n        if type(days) is not int:\n            raise ValueError(\"Days must be an integer value\")\n        if type(hours) is not int:\n            raise ValueError(\"Hours must be an integer value\")\n        if type(minutes) is not int:\n            raise ValueError(\"Minutes must be an integer value\")\n\n        if not enabled:\n            self._check_interval_enabled = False\n        else:\n            self._check_interval_enabled = True\n\n        self._check_interval_months = months\n        self._check_interval_days = days\n        self._check_interval_hours = hours\n        self._check_interval_minutes = minutes\n\n    def __repr__(self):\n        return \"<Module updater from {a}>\".format(a=__file__)\n\n    def __str__(self):\n        return \"Updater, with user: {a}, repository: {b}, url: {c}\".format(\n            a=self._user, b=self._repo, c=self.form_repo_url())\n\n    # -------------------------------------------------------------------------\n    # API-related functions\n    # -------------------------------------------------------------------------\n    def form_repo_url(self):\n        return self._engine.form_repo_url(self)\n\n    def form_tags_url(self):\n        return self._engine.form_tags_url(self)\n\n    def form_branch_url(self, branch):\n        return self._engine.form_branch_url(branch, self)\n\n    def get_tags(self):\n        request = self.form_tags_url()\n        self.print_verbose(\"Getting tags from server\")\n\n        # get all tags, internet call\n        all_tags = self._engine.parse_tags(self.get_api(request), self)\n        if all_tags is not None:\n            self._prefiltered_tag_count = len(all_tags)\n        else:\n            self._prefiltered_tag_count = 0\n            all_tags = list()\n\n        # pre-process to skip tags\n        if self.skip_tag is not None:\n            self._tags = [tg for tg in all_tags if not self.skip_tag(self, tg)]\n        else:\n            self._tags = all_tags\n\n        # get additional branches too, if needed, and place in front\n        # Does NO checking here whether branch is valid\n        if self._include_branches:\n            temp_branches = self._include_branch_list.copy()\n            temp_branches.reverse()\n            for branch in temp_branches:\n                request = self.form_branch_url(branch)\n                include = {\n                    \"name\": branch.title(),\n                    \"zipball_url\": request\n                }\n                self._tags = [include] + self._tags  # append to front\n\n        if self._tags is None:\n            # some error occurred\n            self._tag_latest = None\n            self._tags = list()\n\n        elif self._prefiltered_tag_count == 0 and not self._include_branches:\n            self._tag_latest = None\n            if self._error is None:  # if not None, could have had no internet\n                self._error = \"No releases found\"\n                self._error_msg = \"No releases or tags found in repository\"\n            self.print_verbose(\"No releases or tags found in repository\")\n\n        elif self._prefiltered_tag_count == 0 and self._include_branches:\n            if not self._error:\n                self._tag_latest = self._tags[0]\n            branch = self._include_branch_list[0]\n            self.print_verbose(\"{} branch found, no releases: {}\".format(\n                branch, self._tags[0]))\n\n        elif ((len(self._tags) - len(self._include_branch_list) == 0\n                and self._include_branches)\n                or (len(self._tags) == 0 and not self._include_branches)\n                and self._prefiltered_tag_count > 0):\n            self._tag_latest = None\n            self._error = \"No releases available\"\n            self._error_msg = \"No versions found within compatible version range\"\n            self.print_verbose(self._error_msg)\n\n        else:\n            if not self._include_branches:\n                self._tag_latest = self._tags[0]\n                self.print_verbose(\n                    \"Most recent tag found:\" + str(self._tags[0]['name']))\n            else:\n                # Don't return branch if in list.\n                n = len(self._include_branch_list)\n                self._tag_latest = self._tags[n]  # guaranteed at least len()=n+1\n                self.print_verbose(\n                    \"Most recent tag found:\" + str(self._tags[n]['name']))\n\n    def get_raw(self, url):\n        \"\"\"All API calls to base url.\"\"\"\n        request = urllib.request.Request(url)\n        try:\n            context = ssl._create_unverified_context()\n        except:\n            # Some blender packaged python versions don't have this, largely\n            # useful for local network setups otherwise minimal impact.\n            context = None\n\n        # Setup private request headers if appropriate.\n        if self._engine.token is not None:\n            if self._engine.name == \"gitlab\":\n                request.add_header('PRIVATE-TOKEN', self._engine.token)\n            else:\n                self.print_verbose(\"Tokens not setup for engine yet\")\n\n        # Always set user agent.\n        request.add_header(\n            'User-Agent', \"Python/\" + str(platform.python_version()))\n\n        # Run the request.\n        try:\n            if context:\n                result = urllib.request.urlopen(request, context=context)\n            else:\n                result = urllib.request.urlopen(request)\n        except urllib.error.HTTPError as e:\n            if str(e.code) == \"403\":\n                self._error = \"HTTP error (access denied)\"\n                self._error_msg = str(e.code) + \" - server error response\"\n                print(self._error, self._error_msg)\n            else:\n                self._error = \"HTTP error\"\n                self._error_msg = str(e.code)\n                print(self._error, self._error_msg)\n            self.print_trace()\n            self._update_ready = None\n        except urllib.error.URLError as e:\n            reason = str(e.reason)\n            if \"TLSV1_ALERT\" in reason or \"SSL\" in reason.upper():\n                self._error = \"Connection rejected, download manually\"\n                self._error_msg = reason\n                print(self._error, self._error_msg)\n            else:\n                self._error = \"URL error, check internet connection\"\n                self._error_msg = reason\n                print(self._error, self._error_msg)\n            self.print_trace()\n            self._update_ready = None\n            return None\n        else:\n            result_string = result.read()\n            result.close()\n            return result_string.decode()\n\n    def get_api(self, url):\n        \"\"\"Result of all api calls, decoded into json format.\"\"\"\n        get = None\n        get = self.get_raw(url)\n        if get is not None:\n            try:\n                return json.JSONDecoder().decode(get)\n            except Exception as e:\n                self._error = \"API response has invalid JSON format\"\n                self._error_msg = str(e.reason)\n                self._update_ready = None\n                print(self._error, self._error_msg)\n                self.print_trace()\n                return None\n        else:\n            return None\n\n    def stage_repository(self, url):\n        \"\"\"Create a working directory and download the new files\"\"\"\n\n        local = os.path.join(self._updater_path, \"update_staging\")\n        error = None\n\n        # Make/clear the staging folder, to ensure the folder is always clean.\n        self.print_verbose(\n            \"Preparing staging folder for download:\\n\" + str(local))\n        if os.path.isdir(local):\n            try:\n                shutil.rmtree(local)\n                os.makedirs(local)\n            except:\n                error = \"failed to remove existing staging directory\"\n                self.print_trace()\n        else:\n            try:\n                os.makedirs(local)\n            except:\n                error = \"failed to create staging directory\"\n                self.print_trace()\n\n        if error is not None:\n            self.print_verbose(\"Error: Aborting update, \" + error)\n            self._error = \"Update aborted, staging path error\"\n            self._error_msg = \"Error: {}\".format(error)\n            return False\n\n        if self._backup_current:\n            self.create_backup()\n\n        self.print_verbose(\"Now retrieving the new source zip\")\n        self._source_zip = os.path.join(local, \"source.zip\")\n        self.print_verbose(\"Starting download update zip\")\n        try:\n            request = urllib.request.Request(url)\n            context = ssl._create_unverified_context()\n\n            # Setup private token if appropriate.\n            if self._engine.token is not None:\n                if self._engine.name == \"gitlab\":\n                    request.add_header('PRIVATE-TOKEN', self._engine.token)\n                else:\n                    self.print_verbose(\n                        \"Tokens not setup for selected engine yet\")\n\n            # Always set user agent\n            request.add_header(\n                'User-Agent', \"Python/\" + str(platform.python_version()))\n\n            self.url_retrieve(urllib.request.urlopen(request, context=context),\n                              self._source_zip)\n            # Add additional checks on file size being non-zero.\n            self.print_verbose(\"Successfully downloaded update zip\")\n            return True\n        except Exception as e:\n            self._error = \"Error retrieving download, bad link?\"\n            self._error_msg = \"Error: {}\".format(e)\n            print(\"Error retrieving download, bad link?\")\n            print(\"Error: {}\".format(e))\n            self.print_trace()\n            return False\n\n    def create_backup(self):\n        \"\"\"Save a backup of the current installed addon prior to an update.\"\"\"\n        self.print_verbose(\"Backing up current addon folder\")\n        local = os.path.join(self._updater_path, \"backup\")\n        tempdest = os.path.join(\n            self._addon_root, os.pardir, self._addon + \"_updater_backup_temp\")\n\n        self.print_verbose(\"Backup destination path: \" + str(local))\n\n        if os.path.isdir(local):\n            try:\n                shutil.rmtree(local)\n            except:\n                self.print_verbose(\n                    \"Failed to removed previous backup folder, continuing\")\n                self.print_trace()\n\n        # Remove the temp folder.\n        # Shouldn't exist but could if previously interrupted.\n        if os.path.isdir(tempdest):\n            try:\n                shutil.rmtree(tempdest)\n            except:\n                self.print_verbose(\n                    \"Failed to remove existing temp folder, continuing\")\n                self.print_trace()\n\n        # Make a full addon copy, temporarily placed outside the addon folder.\n        if self._backup_ignore_patterns is not None:\n            try:\n                shutil.copytree(self._addon_root, tempdest,\n                                ignore=shutil.ignore_patterns(\n                                    *self._backup_ignore_patterns))\n            except:\n                print(\"Failed to create backup, still attempting update.\")\n                self.print_trace()\n                return\n        else:\n            try:\n                shutil.copytree(self._addon_root, tempdest)\n            except:\n                print(\"Failed to create backup, still attempting update.\")\n                self.print_trace()\n                return\n        shutil.move(tempdest, local)\n\n        # Save the date for future reference.\n        now = datetime.now()\n        self._json[\"backup_date\"] = \"{m}-{d}-{yr}\".format(\n            m=now.strftime(\"%B\"), d=now.day, yr=now.year)\n        self.save_updater_json()\n\n    def restore_backup(self):\n        \"\"\"Restore the last backed up addon version, user initiated only\"\"\"\n        self.print_verbose(\"Restoring backup, backing up current addon folder\")\n        backuploc = os.path.join(self._updater_path, \"backup\")\n        tempdest = os.path.join(\n            self._addon_root, os.pardir, self._addon + \"_updater_backup_temp\")\n        tempdest = os.path.abspath(tempdest)\n\n        # Move instead contents back in place, instead of copy.\n        shutil.move(backuploc, tempdest)\n        shutil.rmtree(self._addon_root)\n        os.rename(tempdest, self._addon_root)\n\n        self._json[\"backup_date\"] = \"\"\n        self._json[\"just_restored\"] = True\n        self._json[\"just_updated\"] = True\n        self.save_updater_json()\n\n        self.reload_addon()\n\n    def unpack_staged_zip(self, clean=False):\n        \"\"\"Unzip the downloaded file, and validate contents\"\"\"\n        if not os.path.isfile(self._source_zip):\n            self.print_verbose(\"Error, update zip not found\")\n            self._error = \"Install failed\"\n            self._error_msg = \"Downloaded zip not found\"\n            return -1\n\n        # Clear the existing source folder in case previous files remain.\n        outdir = os.path.join(self._updater_path, \"source\")\n        try:\n            shutil.rmtree(outdir)\n            self.print_verbose(\"Source folder cleared\")\n        except:\n            self.print_trace()\n\n        # Create parent directories if needed, would not be relevant unless\n        # installing addon into another location or via an addon manager.\n        try:\n            os.mkdir(outdir)\n        except Exception as err:\n            print(\"Error occurred while making extract dir:\")\n            print(str(err))\n            self.print_trace()\n            self._error = \"Install failed\"\n            self._error_msg = \"Failed to make extract directory\"\n            return -1\n\n        if not os.path.isdir(outdir):\n            print(\"Failed to create source directory\")\n            self._error = \"Install failed\"\n            self._error_msg = \"Failed to create extract directory\"\n            return -1\n\n        self.print_verbose(\n            \"Begin extracting source from zip:\" + str(self._source_zip))\n        with zipfile.ZipFile(self._source_zip, \"r\") as zfile:\n\n            if not zfile:\n                self._error = \"Install failed\"\n                self._error_msg = \"Resulting file is not a zip, cannot extract\"\n                self.print_verbose(self._error_msg)\n                return -1\n\n            # Now extract directly from the first subfolder (not root)\n            # this avoids adding the first subfolder to the path length,\n            # which can be too long if the download has the SHA in the name.\n            zsep = '/'  # Not using os.sep, always the / value even on windows.\n            for name in zfile.namelist():\n                if zsep not in name:\n                    continue\n                top_folder = name[:name.index(zsep) + 1]\n                if name == top_folder + zsep:\n                    continue  # skip top level folder\n                sub_path = name[name.index(zsep) + 1:]\n                if name.endswith(zsep):\n                    try:\n                        os.mkdir(os.path.join(outdir, sub_path))\n                        self.print_verbose(\n                            \"Extract - mkdir: \" + os.path.join(outdir, sub_path))\n                    except OSError as exc:\n                        if exc.errno != errno.EEXIST:\n                            self._error = \"Install failed\"\n                            self._error_msg = \"Could not create folder from zip\"\n                            self.print_trace()\n                            return -1\n                else:\n                    with open(os.path.join(outdir, sub_path), \"wb\") as outfile:\n                        data = zfile.read(name)\n                        outfile.write(data)\n                        self.print_verbose(\n                            \"Extract - create: \" + os.path.join(outdir, sub_path))\n\n        self.print_verbose(\"Extracted source\")\n\n        unpath = os.path.join(self._updater_path, \"source\")\n        if not os.path.isdir(unpath):\n            self._error = \"Install failed\"\n            self._error_msg = \"Extracted path does not exist\"\n            print(\"Extracted path does not exist: \", unpath)\n            return -1\n\n        if self._subfolder_path:\n            self._subfolder_path.replace('/', os.path.sep)\n            self._subfolder_path.replace('\\\\', os.path.sep)\n\n        # Either directly in root of zip/one subfolder, or use specified path.\n        if not os.path.isfile(os.path.join(unpath, \"__init__.py\")):\n            dirlist = os.listdir(unpath)\n            if len(dirlist) > 0:\n                if self._subfolder_path == \"\" or self._subfolder_path is None:\n                    unpath = os.path.join(unpath, dirlist[0])\n                else:\n                    unpath = os.path.join(unpath, self._subfolder_path)\n\n            # Smarter check for additional sub folders for a single folder\n            # containing the __init__.py file.\n            if not os.path.isfile(os.path.join(unpath, \"__init__.py\")):\n                print(\"Not a valid addon found\")\n                print(\"Paths:\")\n                print(dirlist)\n                self._error = \"Install failed\"\n                self._error_msg = \"No __init__ file found in new source\"\n                return -1\n\n        # Merge code with the addon directory, using blender default behavior,\n        # plus any modifiers indicated by user (e.g. force remove/keep).\n        self.deep_merge_directory(self._addon_root, unpath, clean)\n\n        # Now save the json state.\n        # Change to True to trigger the handler on other side if allowing\n        # reloading within same blender session.\n        self._json[\"just_updated\"] = True\n        self.save_updater_json()\n        self.reload_addon()\n        self._update_ready = False\n        return 0\n\n    def deep_merge_directory(self, base, merger, clean=False):\n        \"\"\"Merge folder 'merger' into 'base' without deleting existing\"\"\"\n        if not os.path.exists(base):\n            self.print_verbose(\"Base path does not exist:\" + str(base))\n            return -1\n        elif not os.path.exists(merger):\n            self.print_verbose(\"Merger path does not exist\")\n            return -1\n\n        # Path to be aware of and not overwrite/remove/etc.\n        staging_path = os.path.join(self._updater_path, \"update_staging\")\n\n        # If clean install is enabled, clear existing files ahead of time\n        # note: will not delete the update.json, update folder, staging, or\n        # staging but will delete all other folders/files in addon directory.\n        error = None\n        if clean:\n            try:\n                # Implement clearing of all folders/files, except the updater\n                # folder and updater json.\n                # Careful, this deletes entire subdirectories recursively...\n                # Make sure that base is not a high level shared folder, but\n                # is dedicated just to the addon itself.\n                self.print_verbose(\n                    \"clean=True, clearing addon folder to fresh install state\")\n\n                # Remove root files and folders (except update folder).\n                files = [f for f in os.listdir(base)\n                         if os.path.isfile(os.path.join(base, f))]\n                folders = [f for f in os.listdir(base)\n                           if os.path.isdir(os.path.join(base, f))]\n\n                for f in files:\n                    os.remove(os.path.join(base, f))\n                    self.print_verbose(\n                        \"Clean removing file {}\".format(os.path.join(base, f)))\n                for f in folders:\n                    if os.path.join(base, f) is self._updater_path:\n                        continue\n                    shutil.rmtree(os.path.join(base, f))\n                    self.print_verbose(\n                        \"Clean removing folder and contents {}\".format(\n                            os.path.join(base, f)))\n\n            except Exception as err:\n                error = \"failed to create clean existing addon folder\"\n                print(error, str(err))\n                self.print_trace()\n\n        # Walk through the base addon folder for rules on pre-removing\n        # but avoid removing/altering backup and updater file.\n        for path, dirs, files in os.walk(base):\n            # Prune ie skip updater folder.\n            dirs[:] = [d for d in dirs\n                       if os.path.join(path, d) not in [self._updater_path]]\n            for file in files:\n                for pattern in self.remove_pre_update_patterns:\n                    if fnmatch.filter([file], pattern):\n                        try:\n                            fl = os.path.join(path, file)\n                            os.remove(fl)\n                            self.print_verbose(\"Pre-removed file \" + file)\n                        except OSError:\n                            print(\"Failed to pre-remove \" + file)\n                            self.print_trace()\n\n        # Walk through the temp addon sub folder for replacements\n        # this implements the overwrite rules, which apply after\n        # the above pre-removal rules. This also performs the\n        # actual file copying/replacements.\n        for path, dirs, files in os.walk(merger):\n            # Verify structure works to prune updater sub folder overwriting.\n            dirs[:] = [d for d in dirs\n                       if os.path.join(path, d) not in [self._updater_path]]\n            rel_path = os.path.relpath(path, merger)\n            dest_path = os.path.join(base, rel_path)\n            if not os.path.exists(dest_path):\n                os.makedirs(dest_path)\n            for file in files:\n                # Bring in additional logic around copying/replacing.\n                # Blender default: overwrite .py's, don't overwrite the rest.\n                dest_file = os.path.join(dest_path, file)\n                srcFile = os.path.join(path, file)\n\n                # Decide to replace if file already exists, and copy new over.\n                if os.path.isfile(dest_file):\n                    # Otherwise, check each file for overwrite pattern match.\n                    replaced = False\n                    for pattern in self._overwrite_patterns:\n                        if fnmatch.filter([file], pattern):\n                            replaced = True\n                            break\n                    if replaced:\n                        os.remove(dest_file)\n                        os.rename(srcFile, dest_file)\n                        self.print_verbose(\n                            \"Overwrote file \" + os.path.basename(dest_file))\n                    else:\n                        self.print_verbose(\n                            \"Pattern not matched to {}, not overwritten\".format(\n                                os.path.basename(dest_file)))\n                else:\n                    # File did not previously exist, simply move it over.\n                    os.rename(srcFile, dest_file)\n                    self.print_verbose(\n                        \"New file \" + os.path.basename(dest_file))\n\n        # now remove the temp staging folder and downloaded zip\n        try:\n            shutil.rmtree(staging_path)\n        except:\n            error = (\"Error: Failed to remove existing staging directory, \"\n                     \"consider manually removing \") + staging_path\n            self.print_verbose(error)\n            self.print_trace()\n\n    def reload_addon(self):\n        # if post_update false, skip this function\n        # else, unload/reload addon & trigger popup\n        if not self._auto_reload_post_update:\n            print(\"Restart blender to reload addon and complete update\")\n            return\n\n        self.print_verbose(\"Reloading addon...\")\n        addon_utils.modules(refresh=True)\n        bpy.utils.refresh_script_paths()\n\n        # not allowed in restricted context, such as register module\n        # toggle to refresh\n        if \"addon_disable\" in dir(bpy.ops.wm):  # 2.7\n            bpy.ops.wm.addon_disable(module=self._addon_package)\n            bpy.ops.wm.addon_refresh()\n            bpy.ops.wm.addon_enable(module=self._addon_package)\n            print(\"2.7 reload complete\")\n        else:  # 2.8\n            bpy.ops.preferences.addon_disable(module=self._addon_package)\n            bpy.ops.preferences.addon_refresh()\n            bpy.ops.preferences.addon_enable(module=self._addon_package)\n            print(\"2.8 reload complete\")\n\n    # -------------------------------------------------------------------------\n    # Other non-api functions and setups\n    # -------------------------------------------------------------------------\n    def clear_state(self):\n        self._update_ready = None\n        self._update_link = None\n        self._update_version = None\n        self._source_zip = None\n        self._error = None\n        self._error_msg = None\n\n    def url_retrieve(self, url_file, filepath):\n        \"\"\"Custom urlretrieve implementation\"\"\"\n        chunk = 1024 * 8\n        f = open(filepath, \"wb\")\n        while 1:\n            data = url_file.read(chunk)\n            if not data:\n                # print(\"done.\")\n                break\n            f.write(data)\n            # print(\"Read %s bytes\" % len(data))\n        f.close()\n\n    def version_tuple_from_text(self, text):\n        \"\"\"Convert text into a tuple of numbers (int).\n\n        Should go through string and remove all non-integers, and for any\n        given break split into a different section.\n        \"\"\"\n        if text is None:\n            return ()\n\n        segments = list()\n        tmp = ''\n        for char in str(text):\n            if not char.isdigit():\n                if len(tmp) > 0:\n                    segments.append(int(tmp))\n                    tmp = ''\n            else:\n                tmp += char\n        if len(tmp) > 0:\n            segments.append(int(tmp))\n\n        if len(segments) == 0:\n            self.print_verbose(\"No version strings found text: \" + str(text))\n            if not self._include_branches:\n                return ()\n            else:\n                return (text)\n        return tuple(segments)\n\n    def check_for_update_async(self, callback=None):\n        \"\"\"Called for running check in a background thread\"\"\"\n        is_ready = (\n            self._json is not None\n            and \"update_ready\" in self._json\n            and self._json[\"version_text\"] != dict()\n            and self._json[\"update_ready\"])\n\n        if is_ready:\n            self._update_ready = True\n            self._update_link = self._json[\"version_text\"][\"link\"]\n            self._update_version = str(self._json[\"version_text\"][\"version\"])\n            # Cached update.\n            callback(True)\n            return\n\n        # do the check\n        if not self._check_interval_enabled:\n            return\n        elif self._async_checking:\n            self.print_verbose(\"Skipping async check, already started\")\n            # already running the bg thread\n        elif self._update_ready is None:\n            print(\"{} updater: Running background check for update\".format(\n                  self.addon))\n            self.start_async_check_update(False, callback)\n\n    def check_for_update_now(self, callback=None):\n        self._error = None\n        self._error_msg = None\n        self.print_verbose(\n            \"Check update pressed, first getting current status\")\n        if self._async_checking:\n            self.print_verbose(\"Skipping async check, already started\")\n            return  # already running the bg thread\n        elif self._update_ready is None:\n            self.start_async_check_update(True, callback)\n        else:\n            self._update_ready = None\n            self.start_async_check_update(True, callback)\n\n    def check_for_update(self, now=False):\n        \"\"\"Check for update not in a syncrhonous manner.\n\n        This function is not async, will always return in sequential fashion\n        but should have a parent which calls it in another thread.\n        \"\"\"\n        self.print_verbose(\"Checking for update function\")\n\n        # clear the errors if any\n        self._error = None\n        self._error_msg = None\n\n        # avoid running again in, just return past result if found\n        # but if force now check, then still do it\n        if self._update_ready is not None and not now:\n            return (self._update_ready,\n                    self._update_version,\n                    self._update_link)\n\n        if self._current_version is None:\n            raise ValueError(\"current_version not yet defined\")\n\n        if self._repo is None:\n            raise ValueError(\"repo not yet defined\")\n\n        if self._user is None:\n            raise ValueError(\"username not yet defined\")\n\n        self.set_updater_json()  # self._json\n\n        if not now and not self.past_interval_timestamp():\n            self.print_verbose(\n                \"Aborting check for updated, check interval not reached\")\n            return (False, None, None)\n\n        # check if using tags or releases\n        # note that if called the first time, this will pull tags from online\n        if self._fake_install:\n            self.print_verbose(\n                \"fake_install = True, setting fake version as ready\")\n            self._update_ready = True\n            self._update_version = \"(999,999,999)\"\n            self._update_link = \"http://127.0.0.1\"\n\n            return (self._update_ready,\n                    self._update_version,\n                    self._update_link)\n\n        # Primary internet call, sets self._tags and self._tag_latest.\n        self.get_tags()\n\n        self._json[\"last_check\"] = str(datetime.now())\n        self.save_updater_json()\n\n        # Can be () or ('master') in addition to branches, and version tag.\n        new_version = self.version_tuple_from_text(self.tag_latest)\n\n        if len(self._tags) == 0:\n            self._update_ready = False\n            self._update_version = None\n            self._update_link = None\n            return (False, None, None)\n\n        if not self._include_branches:\n            link = self.select_link(self, self._tags[0])\n        else:\n            n = len(self._include_branch_list)\n            if len(self._tags) == n:\n                # effectively means no tags found on repo\n                # so provide the first one as default\n                link = self.select_link(self, self._tags[0])\n            else:\n                link = self.select_link(self, self._tags[n])\n\n        if new_version == ():\n            self._update_ready = False\n            self._update_version = None\n            self._update_link = None\n            return (False, None, None)\n        elif str(new_version).lower() in self._include_branch_list:\n            # Handle situation where master/whichever branch is included\n            # however, this code effectively is not triggered now\n            # as new_version will only be tag names, not branch names.\n            if not self._include_branch_auto_check:\n                # Don't offer update as ready, but set the link for the\n                # default branch for installing.\n                self._update_ready = False\n                self._update_version = new_version\n                self._update_link = link\n                self.save_updater_json()\n                return (True, new_version, link)\n            else:\n                # Bypass releases and look at timestamp of last update from a\n                # branch compared to now, see if commit values match or not.\n                raise ValueError(\"include_branch_autocheck: NOT YET DEVELOPED\")\n\n        else:\n            # Situation where branches not included.\n            if new_version > self._current_version:\n\n                self._update_ready = True\n                self._update_version = new_version\n                self._update_link = link\n                self.save_updater_json()\n                return (True, new_version, link)\n\n        # If no update, set ready to False from None to show it was checked.\n        self._update_ready = False\n        self._update_version = None\n        self._update_link = None\n        return (False, None, None)\n\n    def set_tag(self, name):\n        \"\"\"Assign the tag name and url to update to\"\"\"\n        tg = None\n        for tag in self._tags:\n            if name == tag[\"name\"]:\n                tg = tag\n                break\n        if tg:\n            new_version = self.version_tuple_from_text(self.tag_latest)\n            self._update_version = new_version\n            self._update_link = self.select_link(self, tg)\n        elif self._include_branches and name in self._include_branch_list:\n            # scenario if reverting to a specific branch name instead of tag\n            tg = name\n            link = self.form_branch_url(tg)\n            self._update_version = name  # this will break things\n            self._update_link = link\n        if not tg:\n            raise ValueError(\"Version tag not found: \" + name)\n\n    def run_update(self, force=False, revert_tag=None, clean=False, callback=None):\n        \"\"\"Runs an install, update, or reversion of an addon from online source\n\n        Arguments:\n            force: Install assigned link, even if self.update_ready is False\n            revert_tag: Version to install, if none uses detected update link\n            clean: not used, but in future could use to totally refresh addon\n            callback: used to run function on update completion\n        \"\"\"\n        self._json[\"update_ready\"] = False\n        self._json[\"ignore\"] = False  # clear ignore flag\n        self._json[\"version_text\"] = dict()\n\n        if revert_tag is not None:\n            self.set_tag(revert_tag)\n            self._update_ready = True\n\n        # clear the errors if any\n        self._error = None\n        self._error_msg = None\n\n        self.print_verbose(\"Running update\")\n\n        if self._fake_install:\n            # Change to True, to trigger the reload/\"update installed\" handler.\n            self.print_verbose(\"fake_install=True\")\n            self.print_verbose(\n                \"Just reloading and running any handler triggers\")\n            self._json[\"just_updated\"] = True\n            self.save_updater_json()\n            if self._backup_current is True:\n                self.create_backup()\n            self.reload_addon()\n            self._update_ready = False\n            res = True  # fake \"success\" zip download flag\n\n        elif not force:\n            if not self._update_ready:\n                self.print_verbose(\"Update stopped, new version not ready\")\n                if callback:\n                    callback(\n                        self._addon_package,\n                        \"Update stopped, new version not ready\")\n                return \"Update stopped, new version not ready\"\n            elif self._update_link is None:\n                # this shouldn't happen if update is ready\n                self.print_verbose(\"Update stopped, update link unavailable\")\n                if callback:\n                    callback(self._addon_package,\n                             \"Update stopped, update link unavailable\")\n                return \"Update stopped, update link unavailable\"\n\n            if revert_tag is None:\n                self.print_verbose(\"Staging update\")\n            else:\n                self.print_verbose(\"Staging install\")\n\n            res = self.stage_repository(self._update_link)\n            if not res:\n                print(\"Error in staging repository: \" + str(res))\n                if callback is not None:\n                    callback(self._addon_package, self._error_msg)\n                return self._error_msg\n            res = self.unpack_staged_zip(clean)\n            if res < 0:\n                if callback:\n                    callback(self._addon_package, self._error_msg)\n                return res\n\n        else:\n            if self._update_link is None:\n                self.print_verbose(\"Update stopped, could not get link\")\n                return \"Update stopped, could not get link\"\n            self.print_verbose(\"Forcing update\")\n\n            res = self.stage_repository(self._update_link)\n            if not res:\n                print(\"Error in staging repository: \" + str(res))\n                if callback:\n                    callback(self._addon_package, self._error_msg)\n                return self._error_msg\n            res = self.unpack_staged_zip(clean)\n            if res < 0:\n                return res\n            # would need to compare against other versions held in tags\n\n        # run the front-end's callback if provided\n        if callback:\n            callback(self._addon_package)\n\n        # return something meaningful, 0 means it worked\n        return 0\n\n    def past_interval_timestamp(self):\n        if not self._check_interval_enabled:\n            return True  # ie this exact feature is disabled\n\n        if \"last_check\" not in self._json or self._json[\"last_check\"] == \"\":\n            return True\n\n        now = datetime.now()\n        last_check = datetime.strptime(\n            self._json[\"last_check\"], \"%Y-%m-%d %H:%M:%S.%f\")\n        offset = timedelta(\n            days=self._check_interval_days + 30 * self._check_interval_months,\n            hours=self._check_interval_hours,\n            minutes=self._check_interval_minutes)\n\n        delta = (now - offset) - last_check\n        if delta.total_seconds() > 0:\n            self.print_verbose(\"Time to check for updates!\")\n            return True\n\n        self.print_verbose(\"Determined it's not yet time to check for updates\")\n        return False\n\n    def get_json_path(self):\n        \"\"\"Returns the full path to the JSON state file used by this updater.\n\n        Will also rename old file paths to addon-specific path if found.\n        \"\"\"\n        json_path = os.path.join(\n            self._updater_path,\n            \"{}_updater_status.json\".format(self._addon_package))\n        old_json_path = os.path.join(self._updater_path, \"updater_status.json\")\n\n        # Rename old file if it exists.\n        try:\n            os.rename(old_json_path, json_path)\n        except FileNotFoundError:\n            pass\n        except Exception as err:\n            print(\"Other OS error occurred while trying to rename old JSON\")\n            print(err)\n            self.print_trace()\n        return json_path\n\n    def set_updater_json(self):\n        \"\"\"Load or initialize JSON dictionary data for updater state\"\"\"\n        if self._updater_path is None:\n            raise ValueError(\"updater_path is not defined\")\n        elif not os.path.isdir(self._updater_path):\n            os.makedirs(self._updater_path)\n\n        jpath = self.get_json_path()\n        if os.path.isfile(jpath):\n            with open(jpath) as data_file:\n                self._json = json.load(data_file)\n                self.print_verbose(\"Read in JSON settings from file\")\n        else:\n            self._json = {\n                \"last_check\": \"\",\n                \"backup_date\": \"\",\n                \"update_ready\": False,\n                \"ignore\": False,\n                \"just_restored\": False,\n                \"just_updated\": False,\n                \"version_text\": dict()\n            }\n            self.save_updater_json()\n\n    def save_updater_json(self):\n        \"\"\"Trigger save of current json structure into file within addon\"\"\"\n        if self._update_ready:\n            if isinstance(self._update_version, tuple):\n                self._json[\"update_ready\"] = True\n                self._json[\"version_text\"][\"link\"] = self._update_link\n                self._json[\"version_text\"][\"version\"] = self._update_version\n            else:\n                self._json[\"update_ready\"] = False\n                self._json[\"version_text\"] = dict()\n        else:\n            self._json[\"update_ready\"] = False\n            self._json[\"version_text\"] = dict()\n\n        jpath = self.get_json_path()\n        if not os.path.isdir(os.path.dirname(jpath)):\n            print(\"State error: Directory does not exist, cannot save json: \",\n                  os.path.basename(jpath))\n            return\n        try:\n            with open(jpath, 'w') as outf:\n                data_out = json.dumps(self._json, indent=4)\n                outf.write(data_out)\n        except:\n            print(\"Failed to open/save data to json: \", jpath)\n            self.print_trace()\n        self.print_verbose(\"Wrote out updater JSON settings with content:\")\n        self.print_verbose(str(self._json))\n\n    def json_reset_postupdate(self):\n        self._json[\"just_updated\"] = False\n        self._json[\"update_ready\"] = False\n        self._json[\"version_text\"] = dict()\n        self.save_updater_json()\n\n    def json_reset_restore(self):\n        self._json[\"just_restored\"] = False\n        self._json[\"update_ready\"] = False\n        self._json[\"version_text\"] = dict()\n        self.save_updater_json()\n        self._update_ready = None  # Reset so you could check update again.\n\n    def ignore_update(self):\n        self._json[\"ignore\"] = True\n        self.save_updater_json()\n\n    # -------------------------------------------------------------------------\n    # ASYNC related methods\n    # -------------------------------------------------------------------------\n    def start_async_check_update(self, now=False, callback=None):\n        \"\"\"Start a background thread which will check for updates\"\"\"\n        if self._async_checking:\n            return\n        self.print_verbose(\"Starting background checking thread\")\n        check_thread = threading.Thread(target=self.async_check_update,\n                                        args=(now, callback,))\n        check_thread.daemon = True\n        self._check_thread = check_thread\n        check_thread.start()\n\n    def async_check_update(self, now, callback=None):\n        \"\"\"Perform update check, run as target of background thread\"\"\"\n        self._async_checking = True\n        self.print_verbose(\"Checking for update now in background\")\n\n        try:\n            self.check_for_update(now=now)\n        except Exception as exception:\n            print(\"Checking for update error:\")\n            print(exception)\n            self.print_trace()\n            if not self._error:\n                self._update_ready = False\n                self._update_version = None\n                self._update_link = None\n                self._error = \"Error occurred\"\n                self._error_msg = \"Encountered an error while checking for updates\"\n\n        self._async_checking = False\n        self._check_thread = None\n\n        if callback:\n            self.print_verbose(\"Finished check update, doing callback\")\n            callback(self._update_ready)\n        self.print_verbose(\"BG thread: Finished check update, no callback\")\n\n    def stop_async_check_update(self):\n        \"\"\"Method to give impression of stopping check for update.\n\n        Currently does nothing but allows user to retry/stop blocking UI from\n        hitting a refresh button. This does not actually stop the thread, as it\n        will complete after the connection timeout regardless. If the thread\n        does complete with a successful response, this will be still displayed\n        on next UI refresh (ie no update, or update available).\n        \"\"\"\n        if self._check_thread is not None:\n            self.print_verbose(\"Thread will end in normal course.\")\n            # however, \"There is no direct kill method on a thread object.\"\n            # better to let it run its course\n            # self._check_thread.stop()\n        self._async_checking = False\n        self._error = None\n        self._error_msg = None\n\n\n# -----------------------------------------------------------------------------\n# Updater Engines\n# -----------------------------------------------------------------------------\n\n\nclass BitbucketEngine:\n    \"\"\"Integration to Bitbucket API for git-formatted repositories\"\"\"\n\n    def __init__(self):\n        self.api_url = 'https://api.bitbucket.org'\n        self.token = None\n        self.name = \"bitbucket\"\n\n    def form_repo_url(self, updater):\n        return \"{}/2.0/repositories/{}/{}\".format(\n            self.api_url, updater.user, updater.repo)\n\n    def form_tags_url(self, updater):\n        return self.form_repo_url(updater) + \"/refs/tags?sort=-name\"\n\n    def form_branch_url(self, branch, updater):\n        return self.get_zip_url(branch, updater)\n\n    def get_zip_url(self, name, updater):\n        return \"https://bitbucket.org/{user}/{repo}/get/{name}.zip\".format(\n            user=updater.user,\n            repo=updater.repo,\n            name=name)\n\n    def parse_tags(self, response, updater):\n        if response is None:\n            return list()\n        return [\n            {\n                \"name\": tag[\"name\"],\n                \"zipball_url\": self.get_zip_url(tag[\"name\"], updater)\n            } for tag in response[\"values\"]]\n\n\nclass GithubEngine:\n    \"\"\"Integration to Github API\"\"\"\n\n    def __init__(self):\n        self.api_url = 'https://api.github.com'\n        self.token = None\n        self.name = \"github\"\n\n    def form_repo_url(self, updater):\n        return \"{}/repos/{}/{}\".format(\n            self.api_url, updater.user, updater.repo)\n\n    def form_tags_url(self, updater):\n        if updater.use_releases:\n            return \"{}/releases\".format(self.form_repo_url(updater))\n        else:\n            return \"{}/tags\".format(self.form_repo_url(updater))\n\n    def form_branch_list_url(self, updater):\n        return \"{}/branches\".format(self.form_repo_url(updater))\n\n    def form_branch_url(self, branch, updater):\n        return \"{}/zipball/{}\".format(self.form_repo_url(updater), branch)\n\n    def parse_tags(self, response, updater):\n        if response is None:\n            return list()\n        return response\n\n\nclass GitlabEngine:\n    \"\"\"Integration to GitLab API\"\"\"\n\n    def __init__(self):\n        self.api_url = 'https://gitlab.com'\n        self.token = None\n        self.name = \"gitlab\"\n\n    def form_repo_url(self, updater):\n        return \"{}/api/v4/projects/{}\".format(self.api_url, updater.repo)\n\n    def form_tags_url(self, updater):\n        return \"{}/repository/tags\".format(self.form_repo_url(updater))\n\n    def form_branch_list_url(self, updater):\n        # does not validate branch name.\n        return \"{}/repository/branches\".format(\n            self.form_repo_url(updater))\n\n    def form_branch_url(self, branch, updater):\n        # Could clash with tag names and if it does, it will download TAG zip\n        # instead of branch zip to get direct path, would need.\n        return \"{}/repository/archive.zip?sha={}\".format(\n            self.form_repo_url(updater), branch)\n\n    def get_zip_url(self, sha, updater):\n        return \"{base}/repository/archive.zip?sha={sha}\".format(\n            base=self.form_repo_url(updater),\n            sha=sha)\n\n    # def get_commit_zip(self, id, updater):\n    # \treturn self.form_repo_url(updater)+\"/repository/archive.zip?sha:\"+id\n\n    def parse_tags(self, response, updater):\n        if response is None:\n            return list()\n        return [\n            {\n                \"name\": tag[\"name\"],\n                \"zipball_url\": self.get_zip_url(tag[\"commit\"][\"id\"], updater)\n            } for tag in response]\n\n\n# -----------------------------------------------------------------------------\n# The module-shared class instance,\n# should be what's imported to other files\n# -----------------------------------------------------------------------------\n\nUpdater = SingletonUpdater()\n"
  },
  {
    "path": "addon_updater_ops.py",
    "content": "# ##### BEGIN GPL LICENSE BLOCK #####\n#\n#  This program is free software; you can redistribute it and/or\n#  modify it under the terms of the GNU General Public License\n#  as published by the Free Software Foundation; either version 2\n#  of the License, or (at your option) any later version.\n#\n#  This program is distributed in the hope that it will be useful,\n#  but WITHOUT ANY WARRANTY; without even the implied warranty of\n#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#  GNU General Public License for more details.\n#\n#  You should have received a copy of the GNU General Public License\n#  along with this program; if not, write to the Free Software Foundation,\n#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n\"\"\"Blender UI integrations for the addon updater.\n\nImplements draw calls, popups, and operators that use the addon_updater.\n\"\"\"\n\nimport os\nimport traceback\n\nimport bpy\nfrom bpy.app.handlers import persistent\n\n# Safely import the updater.\n# Prevents popups for users with invalid python installs e.g. missing libraries\n# and will replace with a fake class instead if it fails (so UI draws work).\ntry:\n    from .addon_updater import Updater as updater\nexcept Exception as e:\n    print(\"ERROR INITIALIZING UPDATER\")\n    print(str(e))\n    traceback.print_exc()\n\n    class SingletonUpdaterNone(object):\n        \"\"\"Fake, bare minimum fields and functions for the updater object.\"\"\"\n\n        def __init__(self):\n            self.invalid_updater = True  # Used to distinguish bad install.\n\n            self.addon = None\n            self.verbose = False\n            self.use_print_traces = True\n            self.error = None\n            self.error_msg = None\n            self.async_checking = None\n\n        def clear_state(self):\n            self.addon = None\n            self.verbose = False\n            self.invalid_updater = True\n            self.error = None\n            self.error_msg = None\n            self.async_checking = None\n\n        def run_update(self, force, callback, clean):\n            pass\n\n        def check_for_update(self, now):\n            pass\n\n    updater = SingletonUpdaterNone()\n    updater.error = \"Error initializing updater module\"\n    updater.error_msg = str(e)\n\n# Must declare this before classes are loaded, otherwise the bl_idname's will\n# not match and have errors. Must be all lowercase and no spaces! Should also\n# be unique among any other addons that could exist (using this updater code),\n# to avoid clashes in operator registration.\nupdater.addon = \"addon_updater_demo\"\n\n\n# -----------------------------------------------------------------------------\n# Blender version utils\n# -----------------------------------------------------------------------------\ndef make_annotations(cls):\n    \"\"\"Add annotation attribute to fields to avoid Blender 2.8+ warnings\"\"\"\n    if not hasattr(bpy.app, \"version\") or bpy.app.version < (2, 80):\n        return cls\n    if bpy.app.version < (2, 93, 0):\n        bl_props = {k: v for k, v in cls.__dict__.items()\n                    if isinstance(v, tuple)}\n    else:\n        bl_props = {k: v for k, v in cls.__dict__.items()\n                    if isinstance(v, bpy.props._PropertyDeferred)}\n    if bl_props:\n        if '__annotations__' not in cls.__dict__:\n            setattr(cls, '__annotations__', {})\n        annotations = cls.__dict__['__annotations__']\n        for k, v in bl_props.items():\n            annotations[k] = v\n            delattr(cls, k)\n    return cls\n\n\ndef layout_split(layout, factor=0.0, align=False):\n    \"\"\"Intermediate method for pre and post blender 2.8 split UI function\"\"\"\n    if not hasattr(bpy.app, \"version\") or bpy.app.version < (2, 80):\n        return layout.split(percentage=factor, align=align)\n    return layout.split(factor=factor, align=align)\n\n\ndef get_user_preferences(context=None):\n    \"\"\"Intermediate method for pre and post blender 2.8 grabbing preferences\"\"\"\n    if not context:\n        context = bpy.context\n    prefs = None\n    if hasattr(context, \"user_preferences\"):\n        prefs = context.user_preferences.addons.get(__package__, None)\n    elif hasattr(context, \"preferences\"):\n        prefs = context.preferences.addons.get(__package__, None)\n    if prefs:\n        return prefs.preferences\n    # To make the addon stable and non-exception prone, return None\n    # raise Exception(\"Could not fetch user preferences\")\n    return None\n\n\n# -----------------------------------------------------------------------------\n# Updater operators\n# -----------------------------------------------------------------------------\n\n\n# Simple popup to prompt use to check for update & offer install if available.\nclass AddonUpdaterInstallPopup(bpy.types.Operator):\n    \"\"\"Check and install update if available\"\"\"\n    bl_label = \"Update {x} addon\".format(x=updater.addon)\n    bl_idname = updater.addon + \".updater_install_popup\"\n    bl_description = \"Popup to check and display current updates available\"\n    bl_options = {'REGISTER', 'INTERNAL'}\n\n    # if true, run clean install - ie remove all files before adding new\n    # equivalent to deleting the addon and reinstalling, except the\n    # updater folder/backup folder remains\n    clean_install = bpy.props.BoolProperty(\n        name=\"Clean install\",\n        description=(\"If enabled, completely clear the addon's folder before \"\n                     \"installing new update, creating a fresh install\"),\n        default=False,\n        options={'HIDDEN'}\n    )\n\n    ignore_enum = bpy.props.EnumProperty(\n        name=\"Process update\",\n        description=\"Decide to install, ignore, or defer new addon update\",\n        items=[\n            (\"install\", \"Update Now\", \"Install update now\"),\n            (\"ignore\", \"Ignore\", \"Ignore this update to prevent future popups\"),\n            (\"defer\", \"Defer\", \"Defer choice till next blender session\")\n        ],\n        options={'HIDDEN'}\n    )\n\n    def check(self, context):\n        return True\n\n    def invoke(self, context, event):\n        return context.window_manager.invoke_props_dialog(self)\n\n    def draw(self, context):\n        layout = self.layout\n        if updater.invalid_updater:\n            layout.label(text=\"Updater module error\")\n            return\n        elif updater.update_ready:\n            col = layout.column()\n            col.scale_y = 0.7\n            col.label(text=\"Update {} ready!\".format(updater.update_version),\n                      icon=\"LOOP_FORWARDS\")\n            col.label(text=\"Choose 'Update Now' & press OK to install, \",\n                      icon=\"BLANK1\")\n            col.label(text=\"or click outside window to defer\", icon=\"BLANK1\")\n            row = col.row()\n            row.prop(self, \"ignore_enum\", expand=True)\n            col.split()\n        elif not updater.update_ready:\n            col = layout.column()\n            col.scale_y = 0.7\n            col.label(text=\"No updates available\")\n            col.label(text=\"Press okay to dismiss dialog\")\n            # add option to force install\n        else:\n            # Case: updater.update_ready = None\n            # we have not yet checked for the update.\n            layout.label(text=\"Check for update now?\")\n\n        # Potentially in future, UI to 'check to select/revert to old version'.\n\n    def execute(self, context):\n        # In case of error importing updater.\n        if updater.invalid_updater:\n            return {'CANCELLED'}\n\n        if updater.manual_only:\n            bpy.ops.wm.url_open(url=updater.website)\n        elif updater.update_ready:\n\n            # Action based on enum selection.\n            if self.ignore_enum == 'defer':\n                return {'FINISHED'}\n            elif self.ignore_enum == 'ignore':\n                updater.ignore_update()\n                return {'FINISHED'}\n\n            res = updater.run_update(force=False,\n                                     callback=post_update_callback,\n                                     clean=self.clean_install)\n\n            # Should return 0, if not something happened.\n            if updater.verbose:\n                if res == 0:\n                    print(\"Updater returned successful\")\n                else:\n                    print(\"Updater returned {}, error occurred\".format(res))\n        elif updater.update_ready is None:\n            _ = updater.check_for_update(now=True)\n\n            # Re-launch this dialog.\n            atr = AddonUpdaterInstallPopup.bl_idname.split(\".\")\n            getattr(getattr(bpy.ops, atr[0]), atr[1])('INVOKE_DEFAULT')\n        else:\n            updater.print_verbose(\"Doing nothing, not ready for update\")\n        return {'FINISHED'}\n\n\n# User preference check-now operator\nclass AddonUpdaterCheckNow(bpy.types.Operator):\n    bl_label = \"Check now for \" + updater.addon + \" update\"\n    bl_idname = updater.addon + \".updater_check_now\"\n    bl_description = \"Check now for an update to the {} addon\".format(\n        updater.addon)\n    bl_options = {'REGISTER', 'INTERNAL'}\n\n    def execute(self, context):\n        if updater.invalid_updater:\n            return {'CANCELLED'}\n\n        if updater.async_checking and updater.error is None:\n            # Check already happened.\n            # Used here to just avoid constant applying settings below.\n            # Ignoring if error, to prevent being stuck on the error screen.\n            return {'CANCELLED'}\n\n        # apply the UI settings\n        settings = get_user_preferences(context)\n        if not settings:\n            updater.print_verbose(\n                \"Could not get {} preferences, update check skipped\".format(\n                    __package__))\n            return {'CANCELLED'}\n\n        updater.set_check_interval(\n            enabled=settings.auto_check_update,\n            months=settings.updater_interval_months,\n            days=settings.updater_interval_days,\n            hours=settings.updater_interval_hours,\n            minutes=settings.updater_interval_minutes)\n\n        # Input is an optional callback function. This function should take a\n        # bool input. If true: update ready, if false: no update ready.\n        updater.check_for_update_now(ui_refresh)\n\n        return {'FINISHED'}\n\n\nclass AddonUpdaterUpdateNow(bpy.types.Operator):\n    bl_label = \"Update \" + updater.addon + \" addon now\"\n    bl_idname = updater.addon + \".updater_update_now\"\n    bl_description = \"Update to the latest version of the {x} addon\".format(\n        x=updater.addon)\n    bl_options = {'REGISTER', 'INTERNAL'}\n\n    # If true, run clean install - ie remove all files before adding new\n    # equivalent to deleting the addon and reinstalling, except the updater\n    # folder/backup folder remains.\n    clean_install = bpy.props.BoolProperty(\n        name=\"Clean install\",\n        description=(\"If enabled, completely clear the addon's folder before \"\n                     \"installing new update, creating a fresh install\"),\n        default=False,\n        options={'HIDDEN'}\n    )\n\n    def execute(self, context):\n\n        # in case of error importing updater\n        if updater.invalid_updater:\n            return {'CANCELLED'}\n\n        if updater.manual_only:\n            bpy.ops.wm.url_open(url=updater.website)\n        if updater.update_ready:\n            # if it fails, offer to open the website instead\n            try:\n                res = updater.run_update(force=False,\n                                         callback=post_update_callback,\n                                         clean=self.clean_install)\n\n                # Should return 0, if not something happened.\n                if updater.verbose:\n                    if res == 0:\n                        print(\"Updater returned successful\")\n                    else:\n                        print(\"Updater error response: {}\".format(res))\n            except Exception as expt:\n                updater._error = \"Error trying to run update\"\n                updater._error_msg = str(expt)\n                updater.print_trace()\n                atr = AddonUpdaterInstallManually.bl_idname.split(\".\")\n                getattr(getattr(bpy.ops, atr[0]), atr[1])('INVOKE_DEFAULT')\n        elif updater.update_ready is None:\n            (update_ready, version, link) = updater.check_for_update(now=True)\n            # Re-launch this dialog.\n            atr = AddonUpdaterInstallPopup.bl_idname.split(\".\")\n            getattr(getattr(bpy.ops, atr[0]), atr[1])('INVOKE_DEFAULT')\n\n        elif not updater.update_ready:\n            self.report({'INFO'}, \"Nothing to update\")\n            return {'CANCELLED'}\n        else:\n            self.report(\n                {'ERROR'}, \"Encountered a problem while trying to update\")\n            return {'CANCELLED'}\n\n        return {'FINISHED'}\n\n\nclass AddonUpdaterUpdateTarget(bpy.types.Operator):\n    bl_label = updater.addon + \" version target\"\n    bl_idname = updater.addon + \".updater_update_target\"\n    bl_description = \"Install a targeted version of the {x} addon\".format(\n        x=updater.addon)\n    bl_options = {'REGISTER', 'INTERNAL'}\n\n    def target_version(self, context):\n        # In case of error importing updater.\n        if updater.invalid_updater:\n            ret = []\n\n        ret = []\n        i = 0\n        for tag in updater.tags:\n            ret.append((tag, tag, \"Select to install \" + tag))\n            i += 1\n        return ret\n\n    target = bpy.props.EnumProperty(\n        name=\"Target version to install\",\n        description=\"Select the version to install\",\n        items=target_version\n    )\n\n    # If true, run clean install - ie remove all files before adding new\n    # equivalent to deleting the addon and reinstalling, except the\n    # updater folder/backup folder remains.\n    clean_install = bpy.props.BoolProperty(\n        name=\"Clean install\",\n        description=(\"If enabled, completely clear the addon's folder before \"\n                     \"installing new update, creating a fresh install\"),\n        default=False,\n        options={'HIDDEN'}\n    )\n\n    @classmethod\n    def poll(cls, context):\n        if updater.invalid_updater:\n            return False\n        return updater.update_ready is not None and len(updater.tags) > 0\n\n    def invoke(self, context, event):\n        return context.window_manager.invoke_props_dialog(self)\n\n    def draw(self, context):\n        layout = self.layout\n        if updater.invalid_updater:\n            layout.label(text=\"Updater error\")\n            return\n        split = layout_split(layout, factor=0.5)\n        sub_col = split.column()\n        sub_col.label(text=\"Select install version\")\n        sub_col = split.column()\n        sub_col.prop(self, \"target\", text=\"\")\n\n    def execute(self, context):\n        # In case of error importing updater.\n        if updater.invalid_updater:\n            return {'CANCELLED'}\n\n        res = updater.run_update(\n            force=False,\n            revert_tag=self.target,\n            callback=post_update_callback,\n            clean=self.clean_install)\n\n        # Should return 0, if not something happened.\n        if res == 0:\n            updater.print_verbose(\"Updater returned successful\")\n        else:\n            updater.print_verbose(\n                \"Updater returned {}, , error occurred\".format(res))\n            return {'CANCELLED'}\n\n        return {'FINISHED'}\n\n\nclass AddonUpdaterInstallManually(bpy.types.Operator):\n    \"\"\"As a fallback, direct the user to download the addon manually\"\"\"\n    bl_label = \"Install update manually\"\n    bl_idname = updater.addon + \".updater_install_manually\"\n    bl_description = \"Proceed to manually install update\"\n    bl_options = {'REGISTER', 'INTERNAL'}\n\n    error = bpy.props.StringProperty(\n        name=\"Error Occurred\",\n        default=\"\",\n        options={'HIDDEN'}\n    )\n\n    def invoke(self, context, event):\n        return context.window_manager.invoke_popup(self)\n\n    def draw(self, context):\n        layout = self.layout\n\n        if updater.invalid_updater:\n            layout.label(text=\"Updater error\")\n            return\n\n        # Display error if a prior autoamted install failed.\n        if self.error != \"\":\n            col = layout.column()\n            col.scale_y = 0.7\n            col.label(text=\"There was an issue trying to auto-install\",\n                      icon=\"ERROR\")\n            col.label(text=\"Press the download button below and install\",\n                      icon=\"BLANK1\")\n            col.label(text=\"the zip file like a normal addon.\", icon=\"BLANK1\")\n        else:\n            col = layout.column()\n            col.scale_y = 0.7\n            col.label(text=\"Install the addon manually\")\n            col.label(text=\"Press the download button below and install\")\n            col.label(text=\"the zip file like a normal addon.\")\n\n        # If check hasn't happened, i.e. accidentally called this menu,\n        # allow to check here.\n\n        row = layout.row()\n\n        if updater.update_link is not None:\n            row.operator(\n                \"wm.url_open\",\n                text=\"Direct download\").url = updater.update_link\n        else:\n            row.operator(\n                \"wm.url_open\",\n                text=\"(failed to retrieve direct download)\")\n            row.enabled = False\n\n            if updater.website is not None:\n                row = layout.row()\n                ops = row.operator(\"wm.url_open\", text=\"Open website\")\n                ops.url = updater.website\n            else:\n                row = layout.row()\n                row.label(text=\"See source website to download the update\")\n\n    def execute(self, context):\n        return {'FINISHED'}\n\n\nclass AddonUpdaterUpdatedSuccessful(bpy.types.Operator):\n    \"\"\"Addon in place, popup telling user it completed or what went wrong\"\"\"\n    bl_label = \"Installation Report\"\n    bl_idname = updater.addon + \".updater_update_successful\"\n    bl_description = \"Update installation response\"\n    bl_options = {'REGISTER', 'INTERNAL', 'UNDO'}\n\n    error = bpy.props.StringProperty(\n        name=\"Error Occurred\",\n        default=\"\",\n        options={'HIDDEN'}\n    )\n\n    def invoke(self, context, event):\n        return context.window_manager.invoke_props_popup(self, event)\n\n    def draw(self, context):\n        layout = self.layout\n\n        if updater.invalid_updater:\n            layout.label(text=\"Updater error\")\n            return\n\n        saved = updater.json\n        if self.error != \"\":\n            col = layout.column()\n            col.scale_y = 0.7\n            col.label(text=\"Error occurred, did not install\", icon=\"ERROR\")\n            if updater.error_msg:\n                msg = updater.error_msg\n            else:\n                msg = self.error\n            col.label(text=str(msg), icon=\"BLANK1\")\n            rw = col.row()\n            rw.scale_y = 2\n            rw.operator(\n                \"wm.url_open\",\n                text=\"Click for manual download.\",\n                icon=\"BLANK1\").url = updater.website\n        elif not updater.auto_reload_post_update:\n            # Tell user to restart blender after an update/restore!\n            if \"just_restored\" in saved and saved[\"just_restored\"]:\n                col = layout.column()\n                col.label(text=\"Addon restored\", icon=\"RECOVER_LAST\")\n                alert_row = col.row()\n                alert_row.alert = True\n                alert_row.operator(\n                    \"wm.quit_blender\",\n                    text=\"Restart blender to reload\",\n                    icon=\"BLANK1\")\n                updater.json_reset_restore()\n            else:\n                col = layout.column()\n                col.label(\n                    text=\"Addon successfully installed\", icon=\"FILE_TICK\")\n                alert_row = col.row()\n                alert_row.alert = True\n                alert_row.operator(\n                    \"wm.quit_blender\",\n                    text=\"Restart blender to reload\",\n                    icon=\"BLANK1\")\n\n        else:\n            # reload addon, but still recommend they restart blender\n            if \"just_restored\" in saved and saved[\"just_restored\"]:\n                col = layout.column()\n                col.scale_y = 0.7\n                col.label(text=\"Addon restored\", icon=\"RECOVER_LAST\")\n                col.label(\n                    text=\"Consider restarting blender to fully reload.\",\n                    icon=\"BLANK1\")\n                updater.json_reset_restore()\n            else:\n                col = layout.column()\n                col.scale_y = 0.7\n                col.label(\n                    text=\"Addon successfully installed\", icon=\"FILE_TICK\")\n                col.label(\n                    text=\"Consider restarting blender to fully reload.\",\n                    icon=\"BLANK1\")\n\n    def execute(self, context):\n        return {'FINISHED'}\n\n\nclass AddonUpdaterRestoreBackup(bpy.types.Operator):\n    \"\"\"Restore addon from backup\"\"\"\n    bl_label = \"Restore backup\"\n    bl_idname = updater.addon + \".updater_restore_backup\"\n    bl_description = \"Restore addon from backup\"\n    bl_options = {'REGISTER', 'INTERNAL'}\n\n    @classmethod\n    def poll(cls, context):\n        try:\n            return os.path.isdir(os.path.join(updater.stage_path, \"backup\"))\n        except:\n            return False\n\n    def execute(self, context):\n        # in case of error importing updater\n        if updater.invalid_updater:\n            return {'CANCELLED'}\n        updater.restore_backup()\n        return {'FINISHED'}\n\n\nclass AddonUpdaterIgnore(bpy.types.Operator):\n    \"\"\"Ignore update to prevent future popups\"\"\"\n    bl_label = \"Ignore update\"\n    bl_idname = updater.addon + \".updater_ignore\"\n    bl_description = \"Ignore update to prevent future popups\"\n    bl_options = {'REGISTER', 'INTERNAL'}\n\n    @classmethod\n    def poll(cls, context):\n        if updater.invalid_updater:\n            return False\n        elif updater.update_ready:\n            return True\n        else:\n            return False\n\n    def execute(self, context):\n        # in case of error importing updater\n        if updater.invalid_updater:\n            return {'CANCELLED'}\n        updater.ignore_update()\n        self.report({\"INFO\"}, \"Open addon preferences for updater options\")\n        return {'FINISHED'}\n\n\nclass AddonUpdaterEndBackground(bpy.types.Operator):\n    \"\"\"Stop checking for update in the background\"\"\"\n    bl_label = \"End background check\"\n    bl_idname = updater.addon + \".end_background_check\"\n    bl_description = \"Stop checking for update in the background\"\n    bl_options = {'REGISTER', 'INTERNAL'}\n\n    def execute(self, context):\n        # in case of error importing updater\n        if updater.invalid_updater:\n            return {'CANCELLED'}\n        updater.stop_async_check_update()\n        return {'FINISHED'}\n\n\n# -----------------------------------------------------------------------------\n# Handler related, to create popups\n# -----------------------------------------------------------------------------\n\n\n# global vars used to prevent duplicate popup handlers\nran_auto_check_install_popup = False\nran_update_success_popup = False\n\n# global var for preventing successive calls\nran_background_check = False\n\n\n@persistent\ndef updater_run_success_popup_handler(scene):\n    global ran_update_success_popup\n    ran_update_success_popup = True\n\n    # in case of error importing updater\n    if updater.invalid_updater:\n        return\n\n    try:\n        if \"scene_update_post\" in dir(bpy.app.handlers):\n            bpy.app.handlers.scene_update_post.remove(\n                updater_run_success_popup_handler)\n        else:\n            bpy.app.handlers.depsgraph_update_post.remove(\n                updater_run_success_popup_handler)\n    except:\n        pass\n\n    atr = AddonUpdaterUpdatedSuccessful.bl_idname.split(\".\")\n    getattr(getattr(bpy.ops, atr[0]), atr[1])('INVOKE_DEFAULT')\n\n\n@persistent\ndef updater_run_install_popup_handler(scene):\n    global ran_auto_check_install_popup\n    ran_auto_check_install_popup = True\n    updater.print_verbose(\"Running the install popup handler.\")\n\n    # in case of error importing updater\n    if updater.invalid_updater:\n        return\n\n    try:\n        if \"scene_update_post\" in dir(bpy.app.handlers):\n            bpy.app.handlers.scene_update_post.remove(\n                updater_run_install_popup_handler)\n        else:\n            bpy.app.handlers.depsgraph_update_post.remove(\n                updater_run_install_popup_handler)\n    except:\n        pass\n\n    if \"ignore\" in updater.json and updater.json[\"ignore\"]:\n        return  # Don't do popup if ignore pressed.\n    elif \"version_text\" in updater.json and updater.json[\"version_text\"].get(\"version\"):\n        version = updater.json[\"version_text\"][\"version\"]\n        ver_tuple = updater.version_tuple_from_text(version)\n\n        if ver_tuple < updater.current_version:\n            # User probably manually installed to get the up to date addon\n            # in here. Clear out the update flag using this function.\n            updater.print_verbose(\n                \"{} updater: appears user updated, clearing flag\".format(\n                    updater.addon))\n            updater.json_reset_restore()\n            return\n    atr = AddonUpdaterInstallPopup.bl_idname.split(\".\")\n    getattr(getattr(bpy.ops, atr[0]), atr[1])('INVOKE_DEFAULT')\n\n\ndef background_update_callback(update_ready):\n    \"\"\"Passed into the updater, background thread updater\"\"\"\n    global ran_auto_check_install_popup\n    updater.print_verbose(\"Running background update callback\")\n\n    # In case of error importing updater.\n    if updater.invalid_updater:\n        return\n    if not updater.show_popups:\n        return\n    if not update_ready:\n        return\n\n    # See if we need add to the update handler to trigger the popup.\n    handlers = []\n    if \"scene_update_post\" in dir(bpy.app.handlers):  # 2.7x\n        handlers = bpy.app.handlers.scene_update_post\n    else:  # 2.8+\n        handlers = bpy.app.handlers.depsgraph_update_post\n    in_handles = updater_run_install_popup_handler in handlers\n\n    if in_handles or ran_auto_check_install_popup:\n        return\n\n    if \"scene_update_post\" in dir(bpy.app.handlers):  # 2.7x\n        bpy.app.handlers.scene_update_post.append(\n            updater_run_install_popup_handler)\n    else:  # 2.8+\n        bpy.app.handlers.depsgraph_update_post.append(\n            updater_run_install_popup_handler)\n    ran_auto_check_install_popup = True\n    updater.print_verbose(\"Attempted popup prompt\")\n\n\ndef post_update_callback(module_name, res=None):\n    \"\"\"Callback for once the run_update function has completed.\n\n    Only makes sense to use this if \"auto_reload_post_update\" == False,\n    i.e. don't auto-restart the addon.\n\n    Arguments:\n        module_name: returns the module name from updater, but unused here.\n        res: If an error occurred, this is the detail string.\n    \"\"\"\n\n    # In case of error importing updater.\n    if updater.invalid_updater:\n        return\n\n    if res is None:\n        # This is the same code as in conditional at the end of the register\n        # function, ie if \"auto_reload_post_update\" == True, skip code.\n        updater.print_verbose(\n            \"{} updater: Running post update callback\".format(updater.addon))\n\n        atr = AddonUpdaterUpdatedSuccessful.bl_idname.split(\".\")\n        getattr(getattr(bpy.ops, atr[0]), atr[1])('INVOKE_DEFAULT')\n        global ran_update_success_popup\n        ran_update_success_popup = True\n    else:\n        # Some kind of error occurred and it was unable to install, offer\n        # manual download instead.\n        atr = AddonUpdaterUpdatedSuccessful.bl_idname.split(\".\")\n        getattr(getattr(bpy.ops, atr[0]), atr[1])('INVOKE_DEFAULT', error=res)\n    return\n\n\ndef ui_refresh(update_status):\n    \"\"\"Redraw the ui once an async thread has completed\"\"\"\n    for windowManager in bpy.data.window_managers:\n        for window in windowManager.windows:\n            for area in window.screen.areas:\n                area.tag_redraw()\n\n\ndef check_for_update_background():\n    \"\"\"Function for asynchronous background check.\n\n    *Could* be called on register, but would be bad practice as the bare\n    minimum code should run at the moment of registration (addon ticked).\n    \"\"\"\n    if updater.invalid_updater:\n        return\n    global ran_background_check\n    if ran_background_check:\n        # Global var ensures check only happens once.\n        return\n    elif updater.update_ready is not None or updater.async_checking:\n        # Check already happened.\n        # Used here to just avoid constant applying settings below.\n        return\n\n    # Apply the UI settings.\n    settings = get_user_preferences(bpy.context)\n    if not settings:\n        return\n    updater.set_check_interval(enabled=settings.auto_check_update,\n                               months=settings.updater_interval_months,\n                               days=settings.updater_interval_days,\n                               hours=settings.updater_interval_hours,\n                               minutes=settings.updater_interval_minutes)\n\n    # Input is an optional callback function. This function should take a bool\n    # input, if true: update ready, if false: no update ready.\n    updater.check_for_update_async(background_update_callback)\n    ran_background_check = True\n\n\ndef check_for_update_nonthreaded(self, context):\n    \"\"\"Can be placed in front of other operators to launch when pressed\"\"\"\n    if updater.invalid_updater:\n        return\n\n    # Only check if it's ready, ie after the time interval specified should\n    # be the async wrapper call here.\n    settings = get_user_preferences(bpy.context)\n    if not settings:\n        if updater.verbose:\n            print(\"Could not get {} preferences, update check skipped\".format(\n                __package__))\n        return\n    updater.set_check_interval(enabled=settings.auto_check_update,\n                               months=settings.updater_interval_months,\n                               days=settings.updater_interval_days,\n                               hours=settings.updater_interval_hours,\n                               minutes=settings.updater_interval_minutes)\n\n    (update_ready, version, link) = updater.check_for_update(now=False)\n    if update_ready:\n        atr = AddonUpdaterInstallPopup.bl_idname.split(\".\")\n        getattr(getattr(bpy.ops, atr[0]), atr[1])('INVOKE_DEFAULT')\n    else:\n        updater.print_verbose(\"No update ready\")\n        self.report({'INFO'}, \"No update ready\")\n\n\ndef show_reload_popup():\n    \"\"\"For use in register only, to show popup after re-enabling the addon.\n\n    Must be enabled by developer.\n    \"\"\"\n    if updater.invalid_updater:\n        return\n    saved_state = updater.json\n    global ran_update_success_popup\n\n    has_state = saved_state is not None\n    just_updated = \"just_updated\" in saved_state\n    updated_info = saved_state[\"just_updated\"]\n\n    if not (has_state and just_updated and updated_info):\n        return\n\n    updater.json_reset_postupdate()  # So this only runs once.\n\n    # No handlers in this case.\n    if not updater.auto_reload_post_update:\n        return\n\n    # See if we need add to the update handler to trigger the popup.\n    handlers = []\n    if \"scene_update_post\" in dir(bpy.app.handlers):  # 2.7x\n        handlers = bpy.app.handlers.scene_update_post\n    else:  # 2.8+\n        handlers = bpy.app.handlers.depsgraph_update_post\n    in_handles = updater_run_success_popup_handler in handlers\n\n    if in_handles or ran_update_success_popup:\n        return\n\n    if \"scene_update_post\" in dir(bpy.app.handlers):  # 2.7x\n        bpy.app.handlers.scene_update_post.append(\n            updater_run_success_popup_handler)\n    else:  # 2.8+\n        bpy.app.handlers.depsgraph_update_post.append(\n            updater_run_success_popup_handler)\n    ran_update_success_popup = True\n\n\n# -----------------------------------------------------------------------------\n# Example UI integrations\n# -----------------------------------------------------------------------------\ndef update_notice_box_ui(self, context):\n    \"\"\"Update notice draw, to add to the end or beginning of a panel.\n\n    After a check for update has occurred, this function will draw a box\n    saying an update is ready, and give a button for: update now, open website,\n    or ignore popup. Ideal to be placed at the end / beginning of a panel.\n    \"\"\"\n\n    if updater.invalid_updater:\n        return\n\n    saved_state = updater.json\n    if not updater.auto_reload_post_update:\n        if \"just_updated\" in saved_state and saved_state[\"just_updated\"]:\n            layout = self.layout\n            box = layout.box()\n            col = box.column()\n            alert_row = col.row()\n            alert_row.alert = True\n            alert_row.operator(\n                \"wm.quit_blender\",\n                text=\"Restart blender\",\n                icon=\"ERROR\")\n            col.label(text=\"to complete update\")\n            return\n\n    # If user pressed ignore, don't draw the box.\n    if \"ignore\" in updater.json and updater.json[\"ignore\"]:\n        return\n    if not updater.update_ready:\n        return\n\n    layout = self.layout\n    box = layout.box()\n    col = box.column(align=True)\n    col.alert = True\n    col.label(text=\"Update ready!\", icon=\"ERROR\")\n    col.alert = False\n    col.separator()\n    row = col.row(align=True)\n    split = row.split(align=True)\n    colL = split.column(align=True)\n    colL.scale_y = 1.5\n    colL.operator(AddonUpdaterIgnore.bl_idname, icon=\"X\", text=\"Ignore\")\n    colR = split.column(align=True)\n    colR.scale_y = 1.5\n    if not updater.manual_only:\n        colR.operator(AddonUpdaterUpdateNow.bl_idname,\n                      text=\"Update\", icon=\"LOOP_FORWARDS\")\n        col.operator(\"wm.url_open\", text=\"Open website\").url = updater.website\n        # ops = col.operator(\"wm.url_open\",text=\"Direct download\")\n        # ops.url=updater.update_link\n        col.operator(AddonUpdaterInstallManually.bl_idname,\n                     text=\"Install manually\")\n    else:\n        # ops = col.operator(\"wm.url_open\", text=\"Direct download\")\n        # ops.url=updater.update_link\n        col.operator(\"wm.url_open\", text=\"Get it now\").url = updater.website\n\n\ndef update_settings_ui(self, context, element=None):\n    \"\"\"Preferences - for drawing with full width inside user preferences\n\n    A function that can be run inside user preferences panel for prefs UI.\n    Place inside UI draw using:\n        addon_updater_ops.update_settings_ui(self, context)\n    or by:\n        addon_updater_ops.update_settings_ui(context)\n    \"\"\"\n\n    # Element is a UI element, such as layout, a row, column, or box.\n    if element is None:\n        element = self.layout\n    box = element.box()\n\n    # In case of error importing updater.\n    if updater.invalid_updater:\n        box.label(text=\"Error initializing updater code:\")\n        box.label(text=updater.error_msg)\n        return\n    settings = get_user_preferences(context)\n    if not settings:\n        box.label(text=\"Error getting updater preferences\", icon='ERROR')\n        return\n\n    # auto-update settings\n    box.label(text=\"Updater Settings\")\n    row = box.row()\n\n    # special case to tell user to restart blender, if set that way\n    if not updater.auto_reload_post_update:\n        saved_state = updater.json\n        if \"just_updated\" in saved_state and saved_state[\"just_updated\"]:\n            row.alert = True\n            row.operator(\"wm.quit_blender\",\n                         text=\"Restart blender to complete update\",\n                         icon=\"ERROR\")\n            return\n\n    split = layout_split(row, factor=0.4)\n    sub_col = split.column()\n    sub_col.prop(settings, \"auto_check_update\")\n    sub_col = split.column()\n\n    if not settings.auto_check_update:\n        sub_col.enabled = False\n    sub_row = sub_col.row()\n    sub_row.label(text=\"Interval between checks\")\n    sub_row = sub_col.row(align=True)\n    check_col = sub_row.column(align=True)\n    check_col.prop(settings, \"updater_interval_months\")\n    check_col = sub_row.column(align=True)\n    check_col.prop(settings, \"updater_interval_days\")\n    check_col = sub_row.column(align=True)\n\n    # Consider un-commenting for local dev (e.g. to set shorter intervals)\n    # check_col.prop(settings,\"updater_interval_hours\")\n    # check_col = sub_row.column(align=True)\n    # check_col.prop(settings,\"updater_interval_minutes\")\n\n    # Checking / managing updates.\n    row = box.row()\n    col = row.column()\n    if updater.error is not None:\n        sub_col = col.row(align=True)\n        sub_col.scale_y = 1\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        if \"ssl\" in updater.error_msg.lower():\n            split.enabled = True\n            split.operator(AddonUpdaterInstallManually.bl_idname,\n                           text=updater.error)\n        else:\n            split.enabled = False\n            split.operator(AddonUpdaterCheckNow.bl_idname,\n                           text=updater.error)\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname,\n                       text=\"\", icon=\"FILE_REFRESH\")\n\n    elif updater.update_ready is None and not updater.async_checking:\n        col.scale_y = 2\n        col.operator(AddonUpdaterCheckNow.bl_idname)\n    elif updater.update_ready is None:  # async is running\n        sub_col = col.row(align=True)\n        sub_col.scale_y = 1\n        split = sub_col.split(align=True)\n        split.enabled = False\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname, text=\"Checking...\")\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterEndBackground.bl_idname, text=\"\", icon=\"X\")\n\n    elif updater.include_branches and \\\n            len(updater.tags) == len(updater.include_branch_list) and not \\\n            updater.manual_only:\n        # No releases found, but still show the appropriate branch.\n        sub_col = col.row(align=True)\n        sub_col.scale_y = 1\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        update_now_txt = \"Update directly to {}\".format(\n            updater.include_branch_list[0])\n        split.operator(AddonUpdaterUpdateNow.bl_idname, text=update_now_txt)\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname,\n                       text=\"\", icon=\"FILE_REFRESH\")\n\n    elif updater.update_ready and not updater.manual_only:\n        sub_col = col.row(align=True)\n        sub_col.scale_y = 1\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterUpdateNow.bl_idname,\n                       text=\"Update now to \" + str(updater.update_version))\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname,\n                       text=\"\", icon=\"FILE_REFRESH\")\n\n    elif updater.update_ready and updater.manual_only:\n        col.scale_y = 2\n        dl_now_txt = \"Download \" + str(updater.update_version)\n        col.operator(\"wm.url_open\",\n                     text=dl_now_txt).url = updater.website\n    else:  # i.e. that updater.update_ready == False.\n        sub_col = col.row(align=True)\n        sub_col.scale_y = 1\n        split = sub_col.split(align=True)\n        split.enabled = False\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname,\n                       text=\"Addon is up to date\")\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname,\n                       text=\"\", icon=\"FILE_REFRESH\")\n\n    if not updater.manual_only:\n        col = row.column(align=True)\n        if updater.include_branches and len(updater.include_branch_list) > 0:\n            branch = updater.include_branch_list[0]\n            col.operator(AddonUpdaterUpdateTarget.bl_idname,\n                         text=\"Install {} / old version\".format(branch))\n        else:\n            col.operator(AddonUpdaterUpdateTarget.bl_idname,\n                         text=\"(Re)install addon version\")\n        last_date = \"none found\"\n        backup_path = os.path.join(updater.stage_path, \"backup\")\n        if \"backup_date\" in updater.json and os.path.isdir(backup_path):\n            if updater.json[\"backup_date\"] == \"\":\n                last_date = \"Date not found\"\n            else:\n                last_date = updater.json[\"backup_date\"]\n        backup_text = \"Restore addon backup ({})\".format(last_date)\n        col.operator(AddonUpdaterRestoreBackup.bl_idname, text=backup_text)\n\n    row = box.row()\n    row.scale_y = 0.7\n    last_check = updater.json[\"last_check\"]\n    if updater.error is not None and updater.error_msg is not None:\n        row.label(text=updater.error_msg)\n    elif last_check:\n        last_check = last_check[0: last_check.index(\".\")]\n        row.label(text=\"Last update check: \" + last_check)\n    else:\n        row.label(text=\"Last update check: Never\")\n\n\ndef update_settings_ui_condensed(self, context, element=None):\n    \"\"\"Preferences - Condensed drawing within preferences.\n\n    Alternate draw for user preferences or other places, does not draw a box.\n    \"\"\"\n\n    # Element is a UI element, such as layout, a row, column, or box.\n    if element is None:\n        element = self.layout\n    row = element.row()\n\n    # In case of error importing updater.\n    if updater.invalid_updater:\n        row.label(text=\"Error initializing updater code:\")\n        row.label(text=updater.error_msg)\n        return\n    settings = get_user_preferences(context)\n    if not settings:\n        row.label(text=\"Error getting updater preferences\", icon='ERROR')\n        return\n\n    # Special case to tell user to restart blender, if set that way.\n    if not updater.auto_reload_post_update:\n        saved_state = updater.json\n        if \"just_updated\" in saved_state and saved_state[\"just_updated\"]:\n            row.alert = True  # mark red\n            row.operator(\n                \"wm.quit_blender\",\n                text=\"Restart blender to complete update\",\n                icon=\"ERROR\")\n            return\n\n    col = row.column()\n    if updater.error is not None:\n        sub_col = col.row(align=True)\n        sub_col.scale_y = 1\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        if \"ssl\" in updater.error_msg.lower():\n            split.enabled = True\n            split.operator(AddonUpdaterInstallManually.bl_idname,\n                           text=updater.error)\n        else:\n            split.enabled = False\n            split.operator(AddonUpdaterCheckNow.bl_idname,\n                           text=updater.error)\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname,\n                       text=\"\", icon=\"FILE_REFRESH\")\n\n    elif updater.update_ready is None and not updater.async_checking:\n        col.scale_y = 2\n        col.operator(AddonUpdaterCheckNow.bl_idname)\n    elif updater.update_ready is None:  # Async is running.\n        sub_col = col.row(align=True)\n        sub_col.scale_y = 1\n        split = sub_col.split(align=True)\n        split.enabled = False\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname, text=\"Checking...\")\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterEndBackground.bl_idname, text=\"\", icon=\"X\")\n\n    elif updater.include_branches and \\\n            len(updater.tags) == len(updater.include_branch_list) and not \\\n            updater.manual_only:\n        # No releases found, but still show the appropriate branch.\n        sub_col = col.row(align=True)\n        sub_col.scale_y = 1\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        now_txt = \"Update directly to \" + str(updater.include_branch_list[0])\n        split.operator(AddonUpdaterUpdateNow.bl_idname, text=now_txt)\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname,\n                       text=\"\", icon=\"FILE_REFRESH\")\n\n    elif updater.update_ready and not updater.manual_only:\n        sub_col = col.row(align=True)\n        sub_col.scale_y = 1\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterUpdateNow.bl_idname,\n                       text=\"Update now to \" + str(updater.update_version))\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname,\n                       text=\"\", icon=\"FILE_REFRESH\")\n\n    elif updater.update_ready and updater.manual_only:\n        col.scale_y = 2\n        dl_txt = \"Download \" + str(updater.update_version)\n        col.operator(\"wm.url_open\", text=dl_txt).url = updater.website\n    else:  # i.e. that updater.update_ready == False.\n        sub_col = col.row(align=True)\n        sub_col.scale_y = 1\n        split = sub_col.split(align=True)\n        split.enabled = False\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname,\n                       text=\"Addon is up to date\")\n        split = sub_col.split(align=True)\n        split.scale_y = 2\n        split.operator(AddonUpdaterCheckNow.bl_idname,\n                       text=\"\", icon=\"FILE_REFRESH\")\n\n    row = element.row()\n    row.prop(settings, \"auto_check_update\")\n\n    row = element.row()\n    row.scale_y = 0.7\n    last_check = updater.json[\"last_check\"]\n    if updater.error is not None and updater.error_msg is not None:\n        row.label(text=updater.error_msg)\n    elif last_check != \"\" and last_check is not None:\n        last_check = last_check[0: last_check.index(\".\")]\n        row.label(text=\"Last check: \" + last_check)\n    else:\n        row.label(text=\"Last check: Never\")\n\n\ndef skip_tag_function(self, tag):\n    \"\"\"A global function for tag skipping.\n\n    A way to filter which tags are displayed, e.g. to limit downgrading too\n    long ago.\n\n    Args:\n        self: The instance of the singleton addon update.\n        tag: the text content of a tag from the repo, e.g. \"v1.2.3\".\n\n    Returns:\n        bool: True to skip this tag name (ie don't allow for downloading this\n            version), or False if the tag is allowed.\n    \"\"\"\n\n    # In case of error importing updater.\n    if self.invalid_updater:\n        return False\n\n    # ---- write any custom code here, return true to disallow version ---- #\n    #\n    # # Filter out e.g. if 'beta' is in name of release\n    # if 'beta' in tag.lower():\n    # \treturn True\n    # ---- write any custom code above, return true to disallow version --- #\n\n    if self.include_branches:\n        for branch in self.include_branch_list:\n            if tag[\"name\"].lower() == branch:\n                return False\n\n    # Function converting string to tuple, ignoring e.g. leading 'v'.\n    # Be aware that this strips out other text that you might otherwise\n    # want to be kept and accounted for when checking tags (e.g. v1.1a vs 1.1b)\n    tupled = self.version_tuple_from_text(tag[\"name\"])\n    if not isinstance(tupled, tuple):\n        return True\n\n    # Select the min tag version - change tuple accordingly.\n    if self.version_min_update is not None:\n        if tupled < self.version_min_update:\n            return True  # Skip if current version below this.\n\n    # Select the max tag version.\n    if self.version_max_update is not None:\n        if tupled >= self.version_max_update:\n            return True  # Skip if current version at or above this.\n\n    # In all other cases, allow showing the tag for updating/reverting.\n    # To simply and always show all tags, this return False could be moved\n    # to the start of the function definition so all tags are allowed.\n    return False\n\n\ndef select_link_function(self, tag):\n    \"\"\"Only customize if trying to leverage \"attachments\" in *GitHub* releases.\n\n    A way to select from one or multiple attached downloadable files from the\n    server, instead of downloading the default release/tag source code.\n    \"\"\"\n\n    # -- Default, universal case (and is the only option for GitLab/Bitbucket)\n    link = tag[\"zipball_url\"]\n\n    # -- Example: select the first (or only) asset instead source code --\n    # if \"assets\" in tag and \"browser_download_url\" in tag[\"assets\"][0]:\n    # \tlink = tag[\"assets\"][0][\"browser_download_url\"]\n\n    # -- Example: select asset based on OS, where multiple builds exist --\n    # # not tested/no error checking, modify to fit your own needs!\n    # # assume each release has three attached builds:\n    # #\t\trelease_windows.zip, release_OSX.zip, release_linux.zip\n    # # This also would logically not be used with \"branches\" enabled\n    # if platform.system() == \"Darwin\": # ie OSX\n    # \tlink = [asset for asset in tag[\"assets\"] if 'OSX' in asset][0]\n    # elif platform.system() == \"Windows\":\n    # \tlink = [asset for asset in tag[\"assets\"] if 'windows' in asset][0]\n    # elif platform.system() == \"Linux\":\n    # \tlink = [asset for asset in tag[\"assets\"] if 'linux' in asset][0]\n\n    return link\n\n\n# -----------------------------------------------------------------------------\n# Register, should be run in the register module itself\n# -----------------------------------------------------------------------------\nclasses = (\n    AddonUpdaterInstallPopup,\n    AddonUpdaterCheckNow,\n    AddonUpdaterUpdateNow,\n    AddonUpdaterUpdateTarget,\n    AddonUpdaterInstallManually,\n    AddonUpdaterUpdatedSuccessful,\n    AddonUpdaterRestoreBackup,\n    AddonUpdaterIgnore,\n    AddonUpdaterEndBackground\n)\n\n\ndef register(bl_info):\n    \"\"\"Registering the operators in this module\"\"\"\n    # Safer failure in case of issue loading module.\n    if updater.error:\n        print(\"Exiting updater registration, \" + updater.error)\n        return\n    updater.clear_state()  # Clear internal vars, avoids reloading oddities.\n\n    # Confirm your updater \"engine\" (Github is default if not specified).\n    updater.engine = \"Github\"\n    # updater.engine = \"GitLab\"\n    # updater.engine = \"Bitbucket\"\n\n    # If using private repository, indicate the token here.\n    # Must be set after assigning the engine.\n    # **WARNING** Depending on the engine, this token can act like a password!!\n    # Only provide a token if the project is *non-public*, see readme for\n    # other considerations and suggestions from a security standpoint.\n    updater.private_token = None  # \"tokenstring\"\n\n    # Choose your own username, must match website (not needed for GitLab).\n    updater.user = \"cgcookie\"\n\n    # Choose your own repository, must match git name for GitHUb and Bitbucket,\n    # for GitLab use project ID (numbers only).\n    updater.repo = \"blender-addon-updater\"\n\n    # updater.addon = # define at top of module, MUST be done first\n\n    # Website for manual addon download, optional but recommended to set.\n    updater.website = \"https://github.com/CGCookie/blender-addon-updater/\"\n\n    # Addon subfolder path.\n    # \"sample/path/to/addon\"\n    # default is \"\" or None, meaning root\n    updater.subfolder_path = \"\"\n\n    # Used to check/compare versions.\n    updater.current_version = bl_info[\"version\"]\n\n    # Optional, to hard-set update frequency, use this here - however, this\n    # demo has this set via UI properties.\n    # updater.set_check_interval(enabled=False, months=0, days=0, hours=0, minutes=2)\n\n    # Optional, consider turning off for production or allow as an option\n    # This will print out additional debugging info to the console\n    updater.verbose = True  # make False for production default\n\n    # Optional, customize where the addon updater processing subfolder is,\n    # essentially a staging folder used by the updater on its own\n    # Needs to be within the same folder as the addon itself\n    # Need to supply a full, absolute path to folder\n    # updater.updater_path = # set path of updater folder, by default:\n    # \t\t\t/addons/{__package__}/{__package__}_updater\n\n    # Auto create a backup of the addon when installing other versions.\n    updater.backup_current = True  # True by default\n\n    # Sample ignore patterns for when creating backup of current during update.\n    updater.backup_ignore_patterns = [\"__pycache__\"]\n    # Alternate example patterns:\n    # updater.backup_ignore_patterns = [\".git\", \"__pycache__\", \"*.bat\", \".gitignore\", \"*.exe\"]\n\n    # Patterns for files to actively overwrite if found in new update file and\n    # are also found in the currently installed addon. Note that by default\n    # (ie if set to []), updates are installed in the same way as blender:\n    # .py files are replaced, but other file types (e.g. json, txt, blend)\n    # will NOT be overwritten if already present in current install. Thus\n    # if you want to automatically update resources/non py files, add them as a\n    # part of the pattern list below so they will always be overwritten by an\n    # update. If a pattern file is not found in new update, no action is taken\n    # NOTE: This does NOT delete anything proactively, rather only defines what\n    # is allowed to be overwritten during an update execution.\n    updater.overwrite_patterns = [\"*.png\", \"*.jpg\", \"README.md\", \"LICENSE.txt\"]\n    # updater.overwrite_patterns = []\n    # other examples:\n    # [\"*\"] means ALL files/folders will be overwritten by update, was the\n    #    behavior pre updater v1.0.4.\n    # [] or [\"*.py\",\"*.pyc\"] matches default blender behavior, ie same effect\n    #    if user installs update manually without deleting the existing addon\n    #    first e.g. if existing install and update both have a resource.blend\n    #    file, the existing installed one will remain.\n    # [\"some.py\"] means if some.py is found in addon update, it will overwrite\n    #    any existing some.py in current addon install, if any.\n    # [\"*.json\"] means all json files found in addon update will overwrite\n    #    those of same name in current install.\n    # [\"*.png\",\"README.md\",\"LICENSE.txt\"] means the readme, license, and all\n    #    pngs will be overwritten by update.\n\n    # Patterns for files to actively remove prior to running update.\n    # Useful if wanting to remove old code due to changes in filenames\n    # that otherwise would accumulate. Note: this runs after taking\n    # a backup (if enabled) but before placing in new update. If the same\n    # file name removed exists in the update, then it acts as if pattern\n    # is placed in the overwrite_patterns property. Note this is effectively\n    # ignored if clean=True in the run_update method.\n    updater.remove_pre_update_patterns = [\"*.py\", \"*.pyc\"]\n    # Note setting [\"*\"] here is equivalent to always running updates with\n    # clean = True in the run_update method, ie the equivalent of a fresh,\n    # new install. This would also delete any resources or user-made/modified\n    # files setting [\"__pycache__\"] ensures the pycache folder always removed.\n    # The configuration of [\"*.py\", \"*.pyc\"] is a safe option as this\n    # will ensure no old python files/caches remain in event different addon\n    # versions have different filenames or structures.\n\n    # Allow branches like 'master' as an option to update to, regardless\n    # of release or version.\n    # Default behavior: releases will still be used for auto check (popup),\n    # but the user has the option from user preferences to directly\n    # update to the master branch or any other branches specified using\n    # the \"install {branch}/older version\" operator.\n    updater.include_branches = True\n\n    # (GitHub only) This options allows using \"releases\" instead of \"tags\",\n    # which enables pulling down release logs/notes, as well as installs update\n    # from release-attached zips (instead of the auto-packaged code generated\n    # with a release/tag). Setting has no impact on BitBucket or GitLab repos.\n    updater.use_releases = False\n    # Note: Releases always have a tag, but a tag may not always be a release.\n    # Therefore, setting True above will filter out any non-annotated tags.\n    # Note 2: Using this option will also display (and filter by) the release\n    # name instead of the tag name, bear this in mind given the\n    # skip_tag_function filtering above.\n\n    # Populate if using \"include_branches\" option above.\n    # Note: updater.include_branch_list defaults to ['master'] branch if set to\n    # none. Example targeting another multiple branches allowed to pull from:\n    # updater.include_branch_list = ['master', 'dev']\n    updater.include_branch_list = None  # None is the equivalent = ['master']\n\n    # Only allow manual install, thus prompting the user to open\n    # the addon's web page to download, specifically: updater.website\n    # Useful if only wanting to get notification of updates but not\n    # directly install.\n    updater.manual_only = False\n\n    # Used for development only, \"pretend\" to install an update to test\n    # reloading conditions.\n    updater.fake_install = False  # Set to true to test callback/reloading.\n\n    # Show popups, ie if auto-check for update is enabled or a previous\n    # check for update in user preferences found a new version, show a popup\n    # (at most once per blender session, and it provides an option to ignore\n    # for future sessions); default behavior is set to True.\n    updater.show_popups = True\n    # note: if set to false, there will still be an \"update ready\" box drawn\n    # using the `update_notice_box_ui` panel function.\n\n    # Override with a custom function on what tags\n    # to skip showing for updater; see code for function above.\n    # Set the min and max versions allowed to install.\n    # Optional, default None\n    # min install (>=) will install this and higher\n    updater.version_min_update = (0, 0, 0)\n    # updater.version_min_update = None  # None or default for no minimum.\n\n    # Max install (<) will install strictly anything lower than this version\n    # number, useful to limit the max version a given user can install (e.g.\n    # if support for a future version of blender is going away, and you don't\n    # want users to be prompted to install a non-functioning addon)\n    # updater.version_max_update = (9,9,9)\n    updater.version_max_update = None  # None or default for no max.\n\n    # Function defined above, customize as appropriate per repository\n    updater.skip_tag = skip_tag_function  # min and max used in this function\n\n    # Function defined above, optionally customize as needed per repository.\n    updater.select_link = select_link_function\n\n    # Recommended false to encourage blender restarts on update completion\n    # Setting this option to True is NOT as stable as false (could cause\n    # blender crashes).\n    updater.auto_reload_post_update = False\n\n    # The register line items for all operators/panels.\n    # If using bpy.utils.register_module(__name__) to register elsewhere\n    # in the addon, delete these lines (also from unregister).\n    for cls in classes:\n        # Apply annotations to remove Blender 2.8+ warnings, no effect on 2.7\n        make_annotations(cls)\n        # Comment out this line if using bpy.utils.register_module(__name__)\n        bpy.utils.register_class(cls)\n\n    # Special situation: we just updated the addon, show a popup to tell the\n    # user it worked. Could enclosed in try/catch in case other issues arise.\n    show_reload_popup()\n\n\ndef unregister():\n    for cls in reversed(classes):\n        # Comment out this line if using bpy.utils.unregister_module(__name__).\n        bpy.utils.unregister_class(cls)\n\n    # Clear global vars since they may persist if not restarting blender.\n    updater.clear_state()  # Clear internal vars, avoids reloading oddities.\n\n    global ran_auto_check_install_popup\n    ran_auto_check_install_popup = False\n\n    global ran_update_success_popup\n    ran_update_success_popup = False\n\n    global ran_background_check\n    ran_background_check = False\n"
  },
  {
    "path": "tests/addon_updater_test.py",
    "content": "# ##### BEGIN GPL LICENSE BLOCK #####\n#\n#  This program is free software; you can redistribute it and/or\n#  modify it under the terms of the GNU General Public License\n#  as published by the Free Software Foundation; either version 2\n#  of the License, or (at your option) any later version.\n#\n#  This program is distributed in the hope that it will be useful,\n#  but WITHOUT ANY WARRANTY; without even the implied warranty of\n#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n#  GNU General Public License for more details.\n#\n#  You should have received a copy of the GNU General Public License\n#  along with this program; if not, write to the Free Software Foundation,\n#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n\"\"\"Tests for the addon updater module python code\n\nRuns tests for each of the engines and major modules, including integration\ntests with the actual services.\n\nHow to run inside blender interface (script editor):\n    Open this file in a blender text editor, and press run.\n    Because some code in the addon_updater.py file still require bpy, it must\n    be run this way in the context of blender. However, tests will run by\n    directly reading the code next this python file in the git repository.\n\nHow to run from command line (run blender from within tests folder)\n    # Run all tests\n    blender -b -P addon_updater_test.py\n\n    # Run all tests within single class\n    blender -b -P addon_updater_test.py -- TestEngines\n\n    # Run specific test\n    blender -b -P addon_updater_test.py -- TestEngines.test_gitlab\n    blender -b -P addon_updater_test.py -- TestFunctions.test_version_tuple_from_text\n\nNote! Running multiple tests in succession could lead to API rate limitations,\nwhich will manifest primarily as errors in the TestEngines unit tests.\n\"\"\"\n\nimport os\nimport sys\nimport unittest\n\nimport bpy\n\nif \"text\" in dir(bpy.context.space_data):\n    # Running inside the python console in blender\n    UPDATER_MODULE_DIR = os.path.dirname(os.path.dirname(\n        bpy.path.abspath(bpy.context.space_data.text.filepath)))\n    QUIT_ON_COMPLETE = False\nelse:\n    # Commandline script passed to blender, directory should be //tests/\n    UPDATER_MODULE_DIR = os.path.dirname(os.getcwd())\n    QUIT_ON_COMPLETE = True\n\nsys.path.append(UPDATER_MODULE_DIR)\nimport addon_updater\n\n\nclass TestEngines(unittest.TestCase):\n\n    def test_gitlab(self):\n        \"\"\"Test the gitlab updater\"\"\"\n\n        updater = addon_updater.SingletonUpdater()\n        updater.engine = \"GitLab\"\n        updater.private_token = None\n        updater.user = \"theduckcow\"\n        updater.repo = \"3645616\"\n        updater.website = \"https://gitlab.com/TheDuckCow/test-updater-gitlab\"\n\n        # Check rate limits\n        # https://docs.gitlab.com/ee/api/README.html#rate-limits\n\n        self.run_engine_test(updater)\n\n    def test_github(self):\n        \"\"\"Test the Github updater\"\"\"\n\n        updater = addon_updater.SingletonUpdater()\n        updater.engine = \"Github\"\n        updater.private_token = None\n        updater.user = \"cgcookie\"\n        updater.repo = \"blender-addon-updater\"\n        updater.website = \"https://github.com/CGCookie/blender-addon-updater\"\n\n        # Check rate limitations (command will show if local limit reached)\n        # curl \"https://api.github.com/rate_limit\"\n        # More info: https://developer.github.com/v3/rate_limit/\n\n        self.run_engine_test(updater)\n\n    def test_bitbucket(self):\n        \"\"\"Test the Bitbucket updater\"\"\"\n\n        updater = addon_updater.SingletonUpdater()\n        updater.engine = \"Bitbucket\"\n        updater.private_token = None\n        updater.user = \"theduckcow\"\n        updater.repo = \"blender-addon-updater-bitbucket\"\n        updater.website = \"https://bitbucket.org/TheDuckCow/blender-addon-updater-bitbucket\"\n\n        # Check rate limitations\n        # https://confluence.atlassian.com/bitbucket/rate-limits-668173227.html\n\n        self.run_engine_test(updater)\n\n    def run_engine_test(self, updater):\n        \"\"\"Run a test for a single engine.\"\"\"\n\n        # Redefine where updating occurs within testing framework\n        os.path.join(UPDATER_MODULE_DIR, \"\")\n        updater._addon = \"test_updater\"\n        updater._addon_package = \"\"\n        updater._updater_path = os.path.join(UPDATER_MODULE_DIR, \"test_updater\")\n        updater._addon_root = UPDATER_MODULE_DIR\n        updater.verbose = False\n\n        updater.current_version = (1, 0, 0)\n        updater.backup_current = False\n        updater.include_branches = True\n        updater.use_releases = False\n\n        # Test raw API call\n        tag_url = updater.form_tags_url()\n        _ = updater.form_branch_url(\"master\")\n        # branch_url = updater.form_branch_url(\"master\")\n        # parsed_tag = updater._engine.parse_tags()\n\n        # verify ths raw request doesn't fail\n        res = updater.get_raw(tag_url)\n        self.assertIsNotNone(res)\n        self.assertNotEqual(res, \"\")\n\n        # verify and check output of parse request\n        res = updater.get_api(tag_url)\n        self.assertIsNotNone(res)\n        self.assertTrue(len(res) > 0)\n\n        # Test the end to end get tag names request\n        tags = updater._get_tag_names()\n        self.assertTrue(len(tags) > 0)\n        # print(\"Found {} tags\".format(len(tags)))\n\n        # Grab link to an archive (should be master for all)\n        link = updater.select_link(updater, updater._tags[0])\n        self.assertIsNotNone(link)\n        # print(link)\n\n        # Test downloading to the staging folder,\n        # clear folder first if needed\n        staged_master = updater.stage_repository(link)\n        self.assertTrue(staged_master)\n\n        # now try downloading a non-master branch\n        link = updater.select_link(updater, updater._tags[1])\n        self.assertIsNotNone(link)\n        staged_tag = updater.stage_repository(link)\n        self.assertTrue(staged_tag)\n\n        # Test the synchronous check function, knowing it should have an update\n        updater._update_ready = None\n        updater.check_for_update()\n        self.assertTrue(updater._update_ready)\n\n        # Test the synchronous check function, knowing it should have no update\n        updater.current_version = (99, 0, 0)\n        updater._update_ready = None\n        updater.check_for_update()\n        self.assertFalse(updater._update_ready)\n\n\nclass TestFunctions(unittest.TestCase):\n    \"\"\"Unit tests not dependent on specific updater engines.\n\n    Test will run with the GitHub engine\n\n    TODO, add:\n        # set_check_interval\n        # create_backup\n        # run_update\n        # restore_backup\n        # unpack_staged_zip\n        # deepMergeDirectory\n        # set_updater_json\n        # set_tag\n        # test with different min/max update versions set\n    \"\"\"\n\n    def test_version_tuple_from_text(self):\n        \"\"\"Test tuple extraction examples\"\"\"\n\n        updater = addon_updater.SingletonUpdater()\n        updater.include_branches = False  # otherwise could treat as branch name\n\n        # structure of: input, expected\n        test_cases = [\n            [\"0.0.0\", (0, 0, 0)],\n            [\"v0.0.0\", (0, 0, 0)],\n            [\"v0.0\", (0, 0)],\n            [\"v0.0 beta\", (0, 0)],\n            [\"version 1,2,3 beta\", (1, 2, 3)]\n        ]\n\n        for case in test_cases:\n            res = updater.version_tuple_from_text(case[0])\n            self.assertEqual(res, case[1])\n\n    def test_reload_callback(self):\n        \"\"\"Test the reload function which disables and re-enables addon\"\"\"\n        updater = addon_updater.SingletonUpdater()\n        updater.auto_reload_post_update = True\n        updater._addon_package = \"blender-addon-updater\"  # test override\n        updater.reload_addon()  # assert no error\n\n\nif __name__ == '__main__':\n    print(\"Running Updater Tests\")\n    if QUIT_ON_COMPLETE:\n        # Running in command line, exclude blender startup args\n        test_args = (sys.argv[sys.argv.index(\"--\") + 1:] if \"--\" in sys.argv else [])\n        sys.argv = [os.path.basename(__file__)] + test_args\n        unittest.main(exit=QUIT_ON_COMPLETE, argv=sys.argv)\n    else:\n        # Running within blender UI script\n        unittest.main(exit=QUIT_ON_COMPLETE)\n"
  }
]