├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── apis ├── categories.go ├── categories_test.go ├── events.go ├── events_test.go ├── site.go ├── site_test.go └── testdata │ ├── categories │ ├── no-categories │ │ └── categories.yaml │ └── valid │ │ └── categories.yaml │ ├── events │ ├── no-events │ │ └── events.yaml │ ├── valid-missing-image │ │ ├── events.yaml │ │ └── img │ │ │ └── event1.jpg │ └── valid │ │ ├── event2.jpg │ │ ├── events.yaml │ │ └── img │ │ └── event1.jpg │ └── sites │ ├── categories-missing │ ├── event2.jpg │ ├── events.yaml │ └── img │ ├── events-missing │ └── categories.yaml │ └── valid │ ├── categories.yaml │ ├── event2.jpg │ ├── events.yaml │ ├── img │ ├── valid-api-output.json │ └── valid-without-codelab.json ├── claattools ├── auth.go ├── auth_test.go ├── fetch.go ├── fetch_test.go └── nodesfilter.go ├── cmd ├── generate │ └── main.go └── serve │ ├── main.go │ ├── server.go │ └── watchers.go ├── codelab ├── codelab.go ├── codelab_test.go ├── dicover_test.go ├── discover.go └── testdata │ ├── bar.png │ ├── codelabgenerated │ ├── gdoc:17GGTeNbjAnnU3jNuKs9SrmQ_DhSqWJPmxxRSbWIjTiY │ │ └── basic-snap-usage │ │ │ ├── codelab.json │ │ │ ├── img │ │ │ ├── 17e5009256674631.png │ │ │ └── f9f287c2e1980df1.png │ │ │ └── index.html │ ├── gdoc:1XUIwNcJj0IIFtza-py5BGDUlWoNeXyO2V0XgNOQvyDQ │ │ └── basic-snap-usage │ │ │ ├── codelab.json │ │ │ └── index.html │ ├── markdown-invalid-generated-html.md │ │ └── example-snap-tutorial │ │ │ ├── codelab.json │ │ │ └── index.html │ ├── markdown-modified-image.md │ │ └── example-snap-tutorial │ │ │ ├── codelab.json │ │ │ ├── img │ │ │ └── 128451a661545188.png │ │ │ └── index.html │ ├── markdown-no-image.md │ │ └── example-snap-tutorial │ │ │ ├── codelab.json │ │ │ ├── img │ │ │ └── .keep │ │ │ └── index.html │ ├── markdown-with-images-duplicate-images.md │ │ └── example-snap-tutorial │ │ │ ├── codelab.json │ │ │ ├── img │ │ │ └── 128451a661545188.png │ │ │ └── index.html │ ├── markdown-with-images-extension-preserved.md │ │ └── example-snap-tutorial │ │ │ ├── codelab.json │ │ │ ├── img │ │ │ ├── 128451a661545188.png │ │ │ └── 38e08f189734d781.jpg │ │ │ └── index.html │ ├── markdown-with-images-online-jpg.md │ │ └── example-snap-tutorial │ │ │ ├── codelab.json │ │ │ ├── img │ │ │ └── 38e08f189734d781.png │ │ │ └── index.html │ ├── markdown-with-images-online.md │ │ └── example-snap-tutorial │ │ │ ├── codelab.json │ │ │ ├── img │ │ │ └── 9d4087c57696f1bc.png │ │ │ └── index.html │ ├── markdown-with-images-relative-upper-path.md │ │ └── example-snap-tutorial │ │ │ ├── codelab.json │ │ │ ├── img │ │ │ └── 128451a661545188.png │ │ │ └── index.html │ ├── markdown-with-images-simple.md │ │ └── example-snap-tutorial │ │ │ ├── codelab.json │ │ │ ├── img │ │ │ └── 128451a661545188.png │ │ │ └── index.html │ └── markdown-with-images.md │ │ └── example-snap-tutorial │ │ ├── codelab.json │ │ ├── img │ │ ├── 128451a661545188.png │ │ ├── 38e08f189734d781.jpg │ │ ├── 38e08f189734d781.png │ │ └── 9d4087c57696f1bc.png │ │ └── index.html │ ├── codelabsrc │ ├── bar.png │ ├── baz.jpg │ ├── foo.png │ ├── markdown-invalid-generated-html.md │ ├── markdown-missing-image.md │ ├── markdown-modified-image.md │ ├── markdown-no-image.md │ ├── markdown-with-images-duplicate-images.md │ ├── markdown-with-images-extension-preserved.md │ ├── markdown-with-images-online-jpg.md │ ├── markdown-with-images-online.md │ ├── markdown-with-images-relative-upper-path.md │ ├── markdown-with-images-simple.md │ └── markdown-with-images.md │ ├── flat │ ├── tut1.md │ └── tut2.md │ ├── flat2 │ └── tut1.md │ ├── nested │ ├── subdir1 │ │ └── subsub │ │ │ ├── tut1.md │ │ │ └── tut2.md │ └── subdir2 │ │ ├── tut1.md │ │ └── tut2.md │ ├── nothing │ └── .keep │ ├── template.html │ ├── withgdoc │ └── gdoc.def │ ├── withgdocduplicate │ └── gdoc.def │ └── withignored │ ├── _part.md │ ├── img │ └── foo.png │ ├── something.blob │ └── tut1.md ├── consts └── consts.go ├── internaltools ├── unique.go └── unique_test.go ├── paths ├── paths.go ├── paths_test.go └── testdata │ ├── nosite │ └── .keep │ ├── partialwebsite │ └── index.html │ └── website │ ├── bower.json │ ├── index.html │ └── subdir │ └── .keep ├── runtests ├── testtools └── tools.go └── websocket ├── websocket_test.go ├── wsClient.go └── wsHub.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Add commands manually 2 | cmd/ 3 | 4 | tests.log -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | go: 3 | - 1.8 4 | # - master 5 | 6 | script: 7 | - ./runtests 8 | - echo -e "==============\nRace detection\n==============" && go test ./... -race 9 | 10 | before_deploy: 11 | - cd cmd/generate && go build 12 | - cd ../serve && go build 13 | - cd ../.. 14 | deploy: 15 | provider: releases 16 | skip_cleanup: true 17 | api_key: 18 | secure: vNIFWGWFgctHet9E422oy/vXdy0EHjhx4guoIKKvtFVZpjOtZpuhTIWq4UUlaYoQT3k9JjaKwzQWp8QrLBP54sXB2cvK32840D1bd4KSm5IrNxwIMRV09S3y0jO191G03dmCKoN4qsojyOY25p1Es94fbCAcyIbFy7JK6Iy8XqhaSG2vGEshBiKLw7pZHUzEnrB+Inzfb4NRCWNL1XdnNugNhxa22AfDZVR9MhS0FNDZWFuEqG5G2Sd43Zf+fDpUsqQ4fj4pHMGt+ifhk5ciiCoCZxWIVrLWg1ANjTuGz3rIKYfFla97KHOoh60bsPd6z5LiIofuaD3mp2APe4Vu+WSnLiotTXUa8m2ZcGGEQHHhSdAhwJ7QwxRGlKbtsb2GrRw4NKJv9weCNS9W+W6Op5YucoFXp1oq3ehqJJzbN3LDxI5VEZ1mDXAAjDmSwio1LzuGQurY3P3360G4b5ezeJJEBDyrvt52eubAk0sr+fxnXxGDv+x5omXlwRM6gXc5w33zNOJiNgHAYxUPQguEzRNTD2EWS5mKEtSVnWsxhsL1pG2ViA0cXjqsshUHOgjIOENSatf1hhdZG9ABbBQQY3GMMNa6MI0bG5b7HxeUGJBHbdwKybZrgwVb3HPj+fllX5ITgj1yTY6d2Wgx4kydDeUZZNdbnddcrOdPTjO8PVY= 19 | file: 20 | - cmd/generate/generate 21 | - cmd/serve/serve 22 | on: 23 | tags: true 24 | repo: ubuntu/tutorial-deployment 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tutorial-deployment 2 | Serve and help generating tutorial deployment for https://tutorials.ubuntu.com 3 | 4 | [![Test Status](https://travis-ci.org/Ubuntu/tutorial-deployment.svg?branch=master)](https://travis-ci.org/Ubuntu/tutorial-deployment) 5 | 6 | Those couple of tools are used in conjonction with https://github.com/canonical-websites/tutorials.ubuntu.com to generate a tutorial website. Those can be written in markdown or google doc, [using the claat google's library](https://github.com/googlecodelabs/tools). 7 | 8 | ## Important note 9 | We are using currently [a fork](https://github.com/didrocks/codelab-ubuntu-tools) of the claat tools as our fixes for the markdown parser are getting reviewed and merged by the google team. 10 | 11 | As this is a more robust deployment procedure, some structural changed were needed and are in progress [there](https://github.com/didrocks/tutorials.ubuntu.com/tree/reformat-tooling). This tool works exclusively with that branch. 12 | 13 | ## Generate 14 | The `generate` command will generate tutorials in **html**, using [Polymerjs](https://www.polymer-project.org/), to be compatible with the aforementioned tutorial source code. 15 | 16 | It fetches in well known places the codelab list and sources (both in **google doc** or **markdown** format), the general events and categories metadata, to generate the desired ouput and API files. 17 | 18 | Every default directories will be detected by the tool if present in the tutorial directories. Arguments and options can tweak this behavior. 19 | 20 | ## Serve 21 | The `serve` command will generate the same codelab content generated on the fly in a temporary directory, but also install watchers on local source files (codelab markdown file or any referenced local images). 22 | 23 | Any save on any of those files will retrigger the corresponding codelab build and API generation, serve by this local http webserver (default port is **8080**) 24 | 25 | Changes are all done in temporary files and not destructive on the tutorial repository. Note that source and webserver paths can be overriden as for the generate command. 26 | -------------------------------------------------------------------------------- /apis/categories.go: -------------------------------------------------------------------------------- 1 | package apis 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "path" 7 | 8 | yaml "gopkg.in/yaml.v2" 9 | 10 | "github.com/ubuntu/tutorial-deployment/paths" 11 | ) 12 | 13 | const ( 14 | categoriesFilename = "categories.yaml" 15 | ) 16 | 17 | // Categories are all supported category for codelabs 18 | type Categories map[string]category 19 | 20 | type category struct { 21 | Lightcolor string `json:"lightcolor"` 22 | Maincolor string `json:"maincolor"` 23 | Secondarycolor string `json:"secondarycolor"` 24 | } 25 | 26 | // NewCategories return all categories for main site 27 | func NewCategories() (*Categories, error) { 28 | c := Categories{} 29 | p := paths.New() 30 | 31 | f := path.Join(p.MetaData, categoriesFilename) 32 | dat, err := ioutil.ReadFile(f) 33 | if err != nil { 34 | return nil, fmt.Errorf("couldn't read from %s: %v", f, err) 35 | } 36 | if err := yaml.Unmarshal(dat, &c); err != nil { 37 | return nil, fmt.Errorf("couldn't decode %s: %v", f, err) 38 | } 39 | 40 | return &c, nil 41 | } 42 | -------------------------------------------------------------------------------- /apis/categories_test.go: -------------------------------------------------------------------------------- 1 | package apis 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "testing" 7 | 8 | "github.com/ubuntu/tutorial-deployment/paths" 9 | ) 10 | 11 | func TestNewCategories(t *testing.T) { 12 | testCases := []struct { 13 | categoriesDir string 14 | 15 | wantCategories Categories 16 | wantErr bool 17 | }{ 18 | {"testdata/categories/valid", 19 | 20 | Categories{"snap": category{Lightcolor: "var(--paper-indigo-300)", Maincolor: "var(--paper-indigo-500)", Secondarycolor: "var(--paper-indigo-700)"}, 21 | "snapcraft": category{Lightcolor: "var(--paper-teal-300)", Maincolor: "var(--paper-teal-500)", Secondarycolor: "var(--paper-teal-700)"}, 22 | "unknown": category{Lightcolor: "#444", Maincolor: "#444", Secondarycolor: "#444"}, 23 | }, 24 | false}, 25 | {"doesnt/exist", nil, true}, 26 | {"testdata/categories/no-categories", Categories{}, false}, 27 | } 28 | for _, tc := range testCases { 29 | t.Run(fmt.Sprintf("create categories for: %+v", tc.categoriesDir), func(t *testing.T) { 30 | // Setup/Teardown 31 | p, teardown := paths.MockPath() 32 | defer teardown() 33 | p.MetaData = tc.categoriesDir 34 | 35 | // Test 36 | c, err := NewCategories() 37 | 38 | if (err != nil) != tc.wantErr { 39 | t.Errorf("NewCategories() error = %v, wantErr %v", err, tc.wantErr) 40 | } 41 | if err != nil { 42 | return 43 | } 44 | 45 | if !reflect.DeepEqual(*c, tc.wantCategories) { 46 | t.Errorf("Generated categories: got %+v; want %+v", *c, tc.wantCategories) 47 | } 48 | }) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /apis/events.go: -------------------------------------------------------------------------------- 1 | package apis 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | "path" 8 | 9 | yaml "gopkg.in/yaml.v2" 10 | 11 | "github.com/ubuntu/tutorial-deployment/consts" 12 | "github.com/ubuntu/tutorial-deployment/paths" 13 | ) 14 | 15 | const ( 16 | eventFilename = "events.yaml" 17 | ) 18 | 19 | // Events are all events planned and grouping some codelabs 20 | type Events map[string]event 21 | 22 | type event struct { 23 | Name string `json:"name"` 24 | Logo string `json:"logo"` 25 | Description string `json:"description"` 26 | } 27 | 28 | // NewEvents return all events for main site 29 | func NewEvents() (*Events, error) { 30 | e := Events{} 31 | p := paths.New() 32 | 33 | f := path.Join(p.MetaData, eventFilename) 34 | dat, err := ioutil.ReadFile(f) 35 | if err != nil { 36 | return nil, fmt.Errorf("couldn't read from %s: %v", f, err) 37 | } 38 | if err := yaml.Unmarshal(dat, &e); err != nil { 39 | return nil, fmt.Errorf("couldn't decode %s: %v", f, err) 40 | } 41 | 42 | return &e, nil 43 | } 44 | 45 | // SaveImages redirect and moves them to api directory 46 | func (evs *Events) SaveImages() error { 47 | p := paths.New() 48 | if err := os.MkdirAll(p.Images, 0775); err != nil { 49 | return fmt.Errorf("couldn't create %s: %v", p.Images, err) 50 | } 51 | for k, e := range *evs { 52 | // path is relative to metadata directory (where the events file is located) 53 | src := path.Join(p.MetaData, e.Logo) 54 | dest := path.Join(p.Images, path.Base(e.Logo)) 55 | e.Logo = path.Join(consts.ImagesURL, path.Base(e.Logo)) 56 | 57 | data, err := ioutil.ReadFile(src) 58 | if err != nil { 59 | return fmt.Errorf("%s doesn't exist: %v", src, err) 60 | } 61 | 62 | if err := ioutil.WriteFile(dest, data, 0644); err != nil { 63 | return fmt.Errorf("couldn't create %s: %v", dest, err) 64 | } 65 | 66 | (*evs)[k] = e 67 | } 68 | return nil 69 | } 70 | -------------------------------------------------------------------------------- /apis/events_test.go: -------------------------------------------------------------------------------- 1 | package apis 2 | 3 | import ( 4 | "fmt" 5 | "path" 6 | "reflect" 7 | "strings" 8 | "testing" 9 | 10 | "github.com/ubuntu/tutorial-deployment/paths" 11 | "github.com/ubuntu/tutorial-deployment/testtools" 12 | 13 | "os" 14 | 15 | "github.com/ubuntu/tutorial-deployment/consts" 16 | ) 17 | 18 | func TestNewEvents(t *testing.T) { 19 | testCases := []struct { 20 | eventsDir string 21 | 22 | wantEvents Events 23 | wantErr bool 24 | }{ 25 | {"testdata/events/valid", 26 | Events{"event-1": event{Name: "Event 1", Logo: "img/event1.jpg", Description: "This workshop is taking place at Event 1."}, 27 | "event-2": event{Name: "Event 2", Logo: "event2.jpg", Description: "This workshop is taking place at Event 2."}, 28 | }, 29 | false}, 30 | {"doesnt/exist", nil, true}, 31 | {"testdata/events/valid-missing-image", // we still load correctly, we don't touch images at this stage 32 | Events{"event-1": event{Name: "Event 1", Logo: "img/event1.jpg", Description: "This workshop is taking place at Event 1."}, 33 | "event-2": event{Name: "Event 2", Logo: "event2.jpg", Description: "This workshop is taking place at Event 2."}, 34 | }, 35 | false}, 36 | {"testdata/events/no-events", Events{}, false}, 37 | } 38 | for _, tc := range testCases { 39 | t.Run(fmt.Sprintf("create events for: %+v", tc.eventsDir), func(t *testing.T) { 40 | // Setup/Teardown 41 | p, teardown := paths.MockPath() 42 | defer teardown() 43 | p.MetaData = tc.eventsDir 44 | 45 | // Test 46 | e, err := NewEvents() 47 | 48 | if (err != nil) != tc.wantErr { 49 | t.Errorf("NewEvents() error = %v, wantErr %v", err, tc.wantErr) 50 | } 51 | if err != nil { 52 | return 53 | } 54 | 55 | if !reflect.DeepEqual(*e, tc.wantEvents) { 56 | t.Errorf("Generated events: got %+v; want %+v", *e, tc.wantEvents) 57 | } 58 | }) 59 | } 60 | } 61 | 62 | func TestSaveImages(t *testing.T) { 63 | testCases := []struct { 64 | eventsDir string 65 | eventsObj Events 66 | 67 | wantEvents Events 68 | wantErr bool 69 | }{ 70 | {"testdata/events/valid", 71 | Events{"event-1": event{Name: "Event 1", Logo: "img/event1.jpg", Description: "This workshop is taking place at Event 1."}, 72 | "event-2": event{Name: "Event 2", Logo: "event2.jpg", Description: "This workshop is taking place at Event 2."}, 73 | }, 74 | Events{"event-1": event{Name: "Event 1", Logo: fmt.Sprintf("%sevent1.jpg", consts.ImagesURL), Description: "This workshop is taking place at Event 1."}, 75 | "event-2": event{Name: "Event 2", Logo: fmt.Sprintf("%sevent2.jpg", consts.ImagesURL), Description: "This workshop is taking place at Event 2."}, 76 | }, 77 | false}, 78 | {"testdata/events/valid-missing-image", 79 | Events{"event-1": event{Name: "Event 1", Logo: "img/event1.jpg", Description: "This workshop is taking place at Event 1."}, 80 | "event-2": event{Name: "Event 2", Logo: "event2.jpg", Description: "This workshop is taking place at Event 2."}, 81 | }, 82 | nil, 83 | true}, 84 | } 85 | for _, tc := range testCases { 86 | t.Run(fmt.Sprintf("save events: %+v", tc.eventsDir), func(t *testing.T) { 87 | // Setup/Teardown 88 | apiout, teardown := testtools.TempDir(t) 89 | defer teardown() 90 | imagesout, teardown := testtools.TempDir(t) 91 | defer teardown() 92 | p, teardown := paths.MockPath() 93 | defer teardown() 94 | p.MetaData = tc.eventsDir 95 | p.API = apiout 96 | p.Images = imagesout 97 | 98 | // Test 99 | err := tc.eventsObj.SaveImages() 100 | 101 | if (err != nil) != tc.wantErr { 102 | t.Errorf("SaveImages() error = %v, wantErr %v", err, tc.wantErr) 103 | } 104 | if err != nil { 105 | return 106 | } 107 | 108 | if !reflect.DeepEqual(tc.eventsObj, tc.wantEvents) { 109 | t.Errorf("Image paths not correctly changed in event: got %+v; want %+v", tc.eventsObj, tc.wantEvents) 110 | } 111 | for _, e := range tc.wantEvents { 112 | imgP := path.Join(p.Images, strings.TrimPrefix(e.Logo, consts.ImagesURL)) 113 | if _, err := os.Stat(imgP); os.IsNotExist(err) { 114 | t.Errorf("%s doesn't exist when we wanted it", imgP) 115 | } 116 | } 117 | }) 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /apis/site.go: -------------------------------------------------------------------------------- 1 | package apis 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | "path" 9 | 10 | "github.com/ubuntu/tutorial-deployment/codelab" 11 | "github.com/ubuntu/tutorial-deployment/paths" 12 | ) 13 | 14 | const apiFileName = "codelabs.json" 15 | 16 | // site API main info 17 | type site struct { 18 | Categories Categories `json:"categories"` 19 | Codelabs []codelab.Codelab `json:"codelabs"` 20 | Events Events `json:"events"` 21 | } 22 | 23 | // GenerateContent for website api, preparing and saving event images already 24 | func GenerateContent(c []codelab.Codelab) ([]byte, error) { 25 | e, err := NewEvents() 26 | if err != nil { 27 | return nil, err 28 | } 29 | if err := e.SaveImages(); err != nil { 30 | return nil, err 31 | } 32 | cat, err := NewCategories() 33 | if err != nil { 34 | return nil, err 35 | } 36 | 37 | s := site{ 38 | Categories: *cat, 39 | Codelabs: c, 40 | Events: *e, 41 | } 42 | return json.MarshalIndent(s, "", " ") 43 | } 44 | 45 | // Save bytes on disk in API file 46 | func Save(dat []byte) error { 47 | p := paths.New() 48 | // ensure that the API dir exists 49 | if err := os.MkdirAll(p.API, 0775); err != nil { 50 | return fmt.Errorf("couldn't create %s: %v", p.API, err) 51 | } 52 | return ioutil.WriteFile(path.Join(p.API, apiFileName), dat, 0644) 53 | } 54 | -------------------------------------------------------------------------------- /apis/site_test.go: -------------------------------------------------------------------------------- 1 | package apis 2 | 3 | import ( 4 | "bytes" 5 | "flag" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "path" 10 | "reflect" 11 | "sort" 12 | "testing" 13 | "time" 14 | 15 | "github.com/didrocks/codelab-ubuntu-tools/claat/types" 16 | "github.com/ubuntu/tutorial-deployment/codelab" 17 | "github.com/ubuntu/tutorial-deployment/paths" 18 | "github.com/ubuntu/tutorial-deployment/testtools" 19 | ) 20 | 21 | var update = flag.Bool("update", false, "update generated files") 22 | 23 | func TestGenerateContent(t *testing.T) { 24 | published := types.LegacyStatus([]string{"Published"}) 25 | exCodelabs := []codelab.Codelab{ 26 | codelab.Codelab{RefURI: "REFPATH1", Codelab: types.Codelab{Meta: types.Meta{ID: "123", Title: "A title", Status: &published, Published: stringToContextTime(t, "1983-09-13"), Summary: "Awesome tutorial", URL: "https://tutorial1.com", Difficulty: 3, Categories: []string{"category1", "category2"}, Tags: []string{"foo", "bar"}, Duration: 60, Feedback: "http://feedback.com", Image: "image.png"}}, FilesWatched: []string{"onefile", "twofiles"}}, 27 | codelab.Codelab{}, 28 | codelab.Codelab{RefURI: "REFPATH2", Codelab: types.Codelab{Meta: types.Meta{ID: "456", Published: stringToContextTime(t, "1984-04-22")}}}, 29 | } 30 | testCases := []struct { 31 | metaDir string 32 | codelabs []codelab.Codelab 33 | 34 | wantReturnPath string 35 | wantAssets []string 36 | wantErr bool 37 | }{ 38 | {"testdata/sites/valid", exCodelabs, "testdata/sites/valid/valid-api-output.json", []string{"event1.jpg", "event2.jpg"}, false}, 39 | {"testdata/sites/categories-missing", exCodelabs, "", nil, true}, 40 | {"testdata/sites/events-missing", exCodelabs, "", nil, true}, 41 | {"testdata/sites/valid", []codelab.Codelab{}, "testdata/sites/valid/valid-without-codelab.json", []string{"event1.jpg", "event2.jpg"}, false}, 42 | } 43 | for _, tc := range testCases { 44 | t.Run(fmt.Sprintf("generate api with codelab: %+v, metadata: %s", tc.codelabs, tc.metaDir), func(t *testing.T) { 45 | // Setup/Teardown 46 | p, teardown := paths.MockPath() 47 | defer teardown() 48 | apidir, teardown := testtools.TempDir(t) 49 | defer teardown() 50 | imagesdir, teardown := testtools.TempDir(t) 51 | defer teardown() 52 | p.MetaData = tc.metaDir 53 | p.API = apidir 54 | p.Images = imagesdir 55 | 56 | // Test 57 | dat, err := GenerateContent(tc.codelabs) 58 | 59 | if (err != nil) != tc.wantErr { 60 | t.Errorf("GenerateAPIcontent() error = %v, wantErr %v", err, tc.wantErr) 61 | } 62 | if err != nil { 63 | return 64 | } 65 | 66 | if *update { 67 | if err := ioutil.WriteFile(tc.wantReturnPath, dat, 0644); err != nil { 68 | t.Fatalf("failed updating %s: %v", tc.wantReturnPath, err) 69 | } 70 | } 71 | 72 | wanted, err := ioutil.ReadFile(tc.wantReturnPath) 73 | if err != nil { 74 | t.Fatalf("couldn't read %s: %v", tc.wantReturnPath, err) 75 | } 76 | 77 | if !bytes.Equal(dat, wanted) { 78 | t.Errorf("generate api: got %s; want %s", dat, wanted) 79 | } 80 | 81 | files, err := ioutil.ReadDir(imagesdir) 82 | if err != nil { 83 | t.Fatalf("couldn't list %s: %v", imagesdir, err) 84 | } 85 | var assets []string 86 | for _, file := range files { 87 | assets = append(assets, file.Name()) 88 | } 89 | sort.Strings(assets) 90 | sort.Strings(tc.wantAssets) 91 | if !reflect.DeepEqual(assets, tc.wantAssets) { 92 | t.Errorf("assets not matching. Got %+v; want %+v", assets, tc.wantAssets) 93 | } 94 | }) 95 | } 96 | } 97 | 98 | func TestSaveAPI(t *testing.T) { 99 | // Setup/Teardown 100 | p, teardown := paths.MockPath() 101 | defer teardown() 102 | apidir, teardown := testtools.TempDir(t) 103 | defer teardown() 104 | p.API = apidir 105 | 106 | content := []byte("something") 107 | if err := Save(content); err != nil { 108 | t.Fatalf("Couldn't save API: %v", err) 109 | } 110 | f := path.Join(apidir, apiFileName) 111 | contentF, err := ioutil.ReadFile(f) 112 | if err != nil { 113 | t.Errorf("%s wasn't saved on disk: %v", f, err) 114 | } 115 | if !reflect.DeepEqual(contentF, content) { 116 | t.Errorf("Got %+v; want %+v", contentF, content) 117 | } 118 | } 119 | 120 | func TestSaveAPINoPath(t *testing.T) { 121 | // Setup/Teardown 122 | p, teardown := paths.MockPath() 123 | defer teardown() 124 | apidir, teardown := testtools.TempDir(t) 125 | defer teardown() 126 | p.API = apidir 127 | 128 | if err := os.Remove(apidir); err != nil { 129 | t.Fatalf("Couldn't remove api dir for test: %v", err) 130 | } 131 | 132 | if err := Save([]byte("something")); err != nil { 133 | t.Fatalf("Couldn't save API on non existing directory: %v", err) 134 | } 135 | f := path.Join(apidir, apiFileName) 136 | if _, err := os.Stat(f); err != nil { 137 | t.Errorf("%s was expected to exist when it doesn't: %v", f, err) 138 | } 139 | } 140 | 141 | func stringToContextTime(t *testing.T, date string) types.ContextTime { 142 | tt, err := time.Parse("2006-01-02", date) 143 | if err != nil { 144 | t.Fatalf("couldn't convert time from %s", date) 145 | } 146 | return types.ContextTime(tt) 147 | } 148 | -------------------------------------------------------------------------------- /apis/testdata/categories/no-categories/categories.yaml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/apis/testdata/categories/no-categories/categories.yaml -------------------------------------------------------------------------------- /apis/testdata/categories/valid/categories.yaml: -------------------------------------------------------------------------------- 1 | snap: 2 | lightcolor: var(--paper-indigo-300) 3 | maincolor: var(--paper-indigo-500) 4 | secondarycolor: var(--paper-indigo-700) 5 | snapcraft: 6 | lightcolor: var(--paper-teal-300) 7 | maincolor: var(--paper-teal-500) 8 | secondarycolor: var(--paper-teal-700) 9 | unknown: 10 | lightcolor: "#444" 11 | maincolor: "#444" 12 | secondarycolor: "#444" 13 | -------------------------------------------------------------------------------- /apis/testdata/events/no-events/events.yaml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/apis/testdata/events/no-events/events.yaml -------------------------------------------------------------------------------- /apis/testdata/events/valid-missing-image/events.yaml: -------------------------------------------------------------------------------- 1 | event-1: 2 | name: "Event 1" 3 | logo: img/event1.jpg 4 | description: "This workshop is taking place at Event 1." 5 | event-2: 6 | name: "Event 2" 7 | logo: event2.jpg 8 | description: "This workshop is taking place at Event 2." 9 | -------------------------------------------------------------------------------- /apis/testdata/events/valid-missing-image/img/event1.jpg: -------------------------------------------------------------------------------- 1 | Image for event 1 -------------------------------------------------------------------------------- /apis/testdata/events/valid/event2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/apis/testdata/events/valid/event2.jpg -------------------------------------------------------------------------------- /apis/testdata/events/valid/events.yaml: -------------------------------------------------------------------------------- 1 | event-1: 2 | name: "Event 1" 3 | logo: img/event1.jpg 4 | description: "This workshop is taking place at Event 1." 5 | event-2: 6 | name: "Event 2" 7 | logo: event2.jpg 8 | description: "This workshop is taking place at Event 2." 9 | -------------------------------------------------------------------------------- /apis/testdata/events/valid/img/event1.jpg: -------------------------------------------------------------------------------- 1 | Image for event 1 -------------------------------------------------------------------------------- /apis/testdata/sites/categories-missing/event2.jpg: -------------------------------------------------------------------------------- 1 | ../../events/valid/event2.jpg -------------------------------------------------------------------------------- /apis/testdata/sites/categories-missing/events.yaml: -------------------------------------------------------------------------------- 1 | ../../events/valid/events.yaml -------------------------------------------------------------------------------- /apis/testdata/sites/categories-missing/img: -------------------------------------------------------------------------------- 1 | ../../events/valid/img/ -------------------------------------------------------------------------------- /apis/testdata/sites/events-missing/categories.yaml: -------------------------------------------------------------------------------- 1 | ../../categories/valid/categories.yaml -------------------------------------------------------------------------------- /apis/testdata/sites/valid/categories.yaml: -------------------------------------------------------------------------------- 1 | ../../categories/valid/categories.yaml -------------------------------------------------------------------------------- /apis/testdata/sites/valid/event2.jpg: -------------------------------------------------------------------------------- 1 | ../../events/valid/event2.jpg -------------------------------------------------------------------------------- /apis/testdata/sites/valid/events.yaml: -------------------------------------------------------------------------------- 1 | ../../events/valid/events.yaml -------------------------------------------------------------------------------- /apis/testdata/sites/valid/img: -------------------------------------------------------------------------------- 1 | ../../events/valid/img/ -------------------------------------------------------------------------------- /apis/testdata/sites/valid/valid-api-output.json: -------------------------------------------------------------------------------- 1 | { 2 | "categories": { 3 | "snap": { 4 | "lightcolor": "var(--paper-indigo-300)", 5 | "maincolor": "var(--paper-indigo-500)", 6 | "secondarycolor": "var(--paper-indigo-700)" 7 | }, 8 | "snapcraft": { 9 | "lightcolor": "var(--paper-teal-300)", 10 | "maincolor": "var(--paper-teal-500)", 11 | "secondarycolor": "var(--paper-teal-700)" 12 | }, 13 | "unknown": { 14 | "lightcolor": "#444", 15 | "maincolor": "#444", 16 | "secondarycolor": "#444" 17 | } 18 | }, 19 | "codelabs": [ 20 | { 21 | "id": "123", 22 | "duration": 60, 23 | "title": "A title", 24 | "summary": "Awesome tutorial", 25 | "theme": "", 26 | "status": [ 27 | "Published" 28 | ], 29 | "category": [ 30 | "category1", 31 | "category2" 32 | ], 33 | "tags": [ 34 | "foo", 35 | "bar" 36 | ], 37 | "feedback": "http://feedback.com", 38 | "difficulty": 3, 39 | "published": "1983-09-13T00:00:00Z", 40 | "image": "image.png", 41 | "url": "https://tutorial1.com" 42 | }, 43 | { 44 | "id": "", 45 | "duration": 0, 46 | "title": "", 47 | "summary": "", 48 | "theme": "", 49 | "status": null, 50 | "category": null, 51 | "tags": null, 52 | "published": "0001-01-01T00:00:00Z", 53 | "url": "" 54 | }, 55 | { 56 | "id": "456", 57 | "duration": 0, 58 | "title": "", 59 | "summary": "", 60 | "theme": "", 61 | "status": null, 62 | "category": null, 63 | "tags": null, 64 | "published": "1984-04-22T00:00:00Z", 65 | "url": "" 66 | } 67 | ], 68 | "events": { 69 | "event-1": { 70 | "name": "Event 1", 71 | "logo": "/images/assets/event1.jpg", 72 | "description": "This workshop is taking place at Event 1." 73 | }, 74 | "event-2": { 75 | "name": "Event 2", 76 | "logo": "/images/assets/event2.jpg", 77 | "description": "This workshop is taking place at Event 2." 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /apis/testdata/sites/valid/valid-without-codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "categories": { 3 | "snap": { 4 | "lightcolor": "var(--paper-indigo-300)", 5 | "maincolor": "var(--paper-indigo-500)", 6 | "secondarycolor": "var(--paper-indigo-700)" 7 | }, 8 | "snapcraft": { 9 | "lightcolor": "var(--paper-teal-300)", 10 | "maincolor": "var(--paper-teal-500)", 11 | "secondarycolor": "var(--paper-teal-700)" 12 | }, 13 | "unknown": { 14 | "lightcolor": "#444", 15 | "maincolor": "#444", 16 | "secondarycolor": "#444" 17 | } 18 | }, 19 | "codelabs": [], 20 | "events": { 21 | "event-1": { 22 | "name": "Event 1", 23 | "logo": "/images/assets/event1.jpg", 24 | "description": "This workshop is taking place at Event 1." 25 | }, 26 | "event-2": { 27 | "name": "Event 2", 28 | "logo": "/images/assets/event2.jpg", 29 | "description": "This workshop is taking place at Event 2." 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /claattools/auth.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // This file is slightly modified from https://github.com/googlecodelabs/tools/blob/master/claat/auth.go 16 | 17 | package claattools 18 | 19 | import ( 20 | "encoding/json" 21 | "fmt" 22 | "io/ioutil" 23 | "log" 24 | "net/http" 25 | "os" 26 | "path" 27 | "sync" 28 | 29 | "golang.org/x/net/context" 30 | "golang.org/x/oauth2" 31 | "golang.org/x/oauth2/google" 32 | ) 33 | 34 | const ( 35 | // auth scopes needed by the program 36 | scopeDriveReadOnly = "https://www.googleapis.com/auth/drive.readonly" 37 | 38 | // program credentials for installed apps 39 | clientID = "127933949931-6nqaiolr3h81makh1qc0p3pbm5h9dt0k.apps.googleusercontent.com" 40 | clientSecret = "127pgIdUPUDhmSKohkHgkFCs" 41 | 42 | // token providers 43 | providerGoogle = "goog" 44 | ) 45 | 46 | var ( 47 | // OAuth2 configs for OOB flow 48 | authConfig = map[string]*oauth2.Config{ 49 | providerGoogle: { 50 | ClientID: clientID, 51 | ClientSecret: clientSecret, 52 | Endpoint: google.Endpoint, 53 | Scopes: []string{scopeDriveReadOnly}, 54 | RedirectURL: "urn:ietf:wg:oauth:2.0:oob", 55 | }, 56 | } 57 | 58 | // reusable HTTP clients 59 | clientsMu sync.Mutex // guards clients 60 | clients map[string]*http.Client 61 | ) 62 | 63 | func init() { 64 | clients = make(map[string]*http.Client) 65 | } 66 | 67 | // DriveClient returns an HTTP client which knows how to perform authenticated 68 | // requests to Google Drive API. 69 | func DriveClient() (*http.Client, error) { 70 | clientsMu.Lock() 71 | defer clientsMu.Unlock() 72 | if hc, ok := clients[providerGoogle]; ok { 73 | return hc, nil 74 | } 75 | ts, err := tokenSource(providerGoogle) 76 | if err != nil { 77 | return nil, err 78 | } 79 | t := &oauth2.Transport{ 80 | Source: ts, 81 | Base: http.DefaultTransport, 82 | } 83 | hc := &http.Client{Transport: t} 84 | clients[providerGoogle] = hc 85 | return hc, nil 86 | } 87 | 88 | // tokenSource creates a new oauth2.TokenSource backed by tokenRefresher, 89 | // using previously stored user credentials if available. 90 | func tokenSource(provider string) (oauth2.TokenSource, error) { 91 | conf := authConfig[provider] 92 | if conf == nil { 93 | return nil, fmt.Errorf("no auth config for %q", provider) 94 | } 95 | t, err := readToken(provider) 96 | if err != nil { 97 | t, err = authorize(conf) 98 | } 99 | if err != nil { 100 | return nil, fmt.Errorf("unable to obtain access token for %q: %v", provider, err) 101 | } 102 | cache := &cachedTokenSource{ 103 | src: conf.TokenSource(context.Background(), t), 104 | provider: provider, 105 | config: conf, 106 | } 107 | return oauth2.ReuseTokenSource(nil, cache), nil 108 | } 109 | 110 | // authorize performs user aufthorization flow, asking for permissions grant. 111 | func authorize(conf *oauth2.Config) (*oauth2.Token, error) { 112 | aurl := conf.AuthCodeURL("unused", oauth2.AccessTypeOffline) 113 | fmt.Printf("Authorize me at following URL, please:\n%s\n\nCode: ", aurl) 114 | var code string 115 | if _, err := fmt.Scan(&code); err != nil { 116 | return nil, err 117 | } 118 | fmt.Printf("Could scan &code: %s\n", code) 119 | return conf.Exchange(context.Background(), code) 120 | } 121 | 122 | // cachedTokenSource stores tokens returned from src on local disk. 123 | // It is usually combined with oauth2.ReuseTokenSource. 124 | type cachedTokenSource struct { 125 | src oauth2.TokenSource 126 | provider string 127 | config *oauth2.Config 128 | } 129 | 130 | func (c *cachedTokenSource) Token() (*oauth2.Token, error) { 131 | t, err := c.src.Token() 132 | if err != nil { 133 | t, err = authorize(c.config) 134 | } 135 | if err != nil { 136 | return nil, err 137 | } 138 | writeToken(c.provider, t) 139 | return t, nil 140 | } 141 | 142 | // readToken deserializes token from local disk. 143 | func readToken(provider string) (*oauth2.Token, error) { 144 | l, err := tokenLocation(provider) 145 | if err != nil { 146 | return nil, err 147 | } 148 | b, err := ioutil.ReadFile(l) 149 | if err != nil { 150 | return nil, err 151 | } 152 | t := &oauth2.Token{} 153 | return t, json.Unmarshal(b, t) 154 | } 155 | 156 | // writeToken serializes token tok to local disk. 157 | func writeToken(provider string, tok *oauth2.Token) error { 158 | l, err := tokenLocation(provider) 159 | if err != nil { 160 | return err 161 | } 162 | w, err := os.Create(l) 163 | if err != nil { 164 | return err 165 | } 166 | defer w.Close() 167 | b, err := json.MarshalIndent(tok, "", " ") 168 | if err != nil { 169 | return err 170 | } 171 | _, err = w.Write(b) 172 | return err 173 | } 174 | 175 | // tokenLocation returns a local file path, suitable for storing user credentials. 176 | func tokenLocation(provider string) (string, error) { 177 | d := homedir() 178 | if d == "" { 179 | log.Printf("WARNING: unable to identify user home dir") 180 | } 181 | d = path.Join(d, ".config", "ubuntu-tutorials") 182 | if err := os.MkdirAll(d, 0700); err != nil { 183 | return "", err 184 | } 185 | return path.Join(d, provider+"-cred.json"), nil 186 | } 187 | 188 | func homedir() string { 189 | if v := os.Getenv("HOME"); v != "" { 190 | return v 191 | } 192 | d, p := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH") 193 | if d != "" && p != "" { 194 | return d + p 195 | } 196 | return os.Getenv("USERPROFILE") 197 | } 198 | -------------------------------------------------------------------------------- /claattools/auth_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // This file is slightly modified from https://github.com/googlecodelabs/tools/blob/master/claat/auth.go 16 | 17 | package claattools 18 | 19 | import ( 20 | "net/http" 21 | "reflect" 22 | "testing" 23 | ) 24 | 25 | func Test_driveClient(t *testing.T) { 26 | tests := []struct { 27 | name string 28 | want *http.Client 29 | wantErr bool 30 | }{ 31 | // TODO: Add test cases. 32 | } 33 | for _, tt := range tests { 34 | t.Run(tt.name, func(t *testing.T) { 35 | got, err := DriveClient() 36 | if (err != nil) != tt.wantErr { 37 | t.Errorf("driveClient() error = %v, wantErr %v", err, tt.wantErr) 38 | return 39 | } 40 | if !reflect.DeepEqual(got, tt.want) { 41 | t.Errorf("driveClient() = %v, want %v", got, tt.want) 42 | } 43 | }) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /claattools/fetch.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Most of this file is heavily inspired from https://github.com/googlecodelabs/tools/blob/master/claat/fetch.go 16 | 17 | package claattools 18 | 19 | import ( 20 | "encoding/json" 21 | "fmt" 22 | "io" 23 | "io/ioutil" 24 | "math" 25 | "math/rand" 26 | "net/http" 27 | "net/url" 28 | "os" 29 | "strings" 30 | "time" 31 | 32 | "github.com/ubuntu/tutorial-deployment/consts" 33 | ) 34 | 35 | const ( 36 | // supported codelab source types must be registered parsers 37 | typeGdoc = "gdoc" // Google Docs doc 38 | typeMarkdown = "md" // Markdown text 39 | ) 40 | 41 | // Resource is a codelab Resource, loaded from local file 42 | // or fetched from remote location. 43 | type Resource struct { 44 | Body io.ReadCloser // resource body 45 | Mod time.Time // last update of content 46 | Type string // Either gdoc or md 47 | } 48 | 49 | // driveAPI is a base URL for Drive API 50 | const driveAPI = "https://www.googleapis.com/drive/v3" 51 | 52 | // Fetch retrieves codelab doc either from local disk 53 | // or a remote location. 54 | // The caller is responsible for closing returned stream. 55 | func Fetch(name string) (*Resource, error) { 56 | fi, err := os.Stat(name) 57 | if os.IsNotExist(err) { 58 | return FetchRemote(name, false) 59 | } 60 | r, err := os.Open(name) 61 | if err != nil { 62 | return nil, err 63 | } 64 | return &Resource{ 65 | Body: r, 66 | Mod: fi.ModTime(), 67 | Type: typeMarkdown, 68 | }, nil 69 | } 70 | 71 | // FetchRemote retrieves resource r from the network. 72 | // 73 | // If urlStr is not a URL, i.e. does not have the host part and is prepended by gdoc:, it is considered to be 74 | // a Google Doc ID and fetched accordingly. Otherwise, a simple GET request 75 | // is used to retrieve the contents. 76 | // 77 | // The caller is responsible for closing returned stream. 78 | // If nometa is true, Resource.mod may have zero value. 79 | func FetchRemote(urlStr string, nometa bool) (*Resource, error) { 80 | u, err := url.Parse(urlStr) 81 | if err != nil { 82 | return nil, err 83 | } 84 | if (u.Host == "" && strings.HasPrefix(urlStr, consts.GdocPrefix)) || u.Host == "docs.google.com" { 85 | return fetchDriveFile(strings.TrimPrefix(urlStr, consts.GdocPrefix), nometa) 86 | } 87 | // If there is still no host, not a gdoc neither a local existing path, fail immediately 88 | if u.Host == "" { 89 | return nil, fmt.Errorf("%s doesn't exist", urlStr) 90 | } 91 | return fetchRemoteFile(urlStr) 92 | } 93 | 94 | // fetchRemoteFile retrieves codelab resource from url. 95 | // It is a special case of fetchRemote function. 96 | func fetchRemoteFile(url string) (*Resource, error) { 97 | res, err := retryGet(nil, url, 3) 98 | if err != nil { 99 | return nil, err 100 | } 101 | t, err := http.ParseTime(res.Header.Get("last-modified")) 102 | if err != nil { 103 | t = time.Now() 104 | } 105 | return &Resource{ 106 | Body: res.Body, 107 | Mod: t, 108 | Type: typeMarkdown, 109 | }, nil 110 | } 111 | 112 | // FetchRemoteBytes get bytes from a remote entity, including drive ID 113 | func FetchRemoteBytes(client *http.Client, url string, n int) ([]byte, error) { 114 | res, err := retryGet(client, url, n) 115 | if err != nil { 116 | return nil, err 117 | } 118 | defer res.Body.Close() 119 | return ioutil.ReadAll(res.Body) 120 | } 121 | 122 | // fetchDriveFile uses Drive API to retrieve HTML representation of a Google Doc. 123 | // See https://developers.google.com/drive/web/manage-downloads#downloading_google_documents 124 | // for more details. 125 | // 126 | // If nometa is true, resource.mod will have zero value. 127 | func fetchDriveFile(id string, nometa bool) (*Resource, error) { 128 | id = gdocID(id) 129 | exportURL := gdocExportURL(id) 130 | client, err := DriveClient() 131 | if err != nil { 132 | return nil, err 133 | } 134 | 135 | if nometa { 136 | res, err := retryGet(client, exportURL, 7) 137 | if err != nil { 138 | return nil, err 139 | } 140 | return &Resource{Body: res.Body, Type: typeGdoc}, nil 141 | } 142 | 143 | u := fmt.Sprintf("%s/files/%s?fields=id,mimeType,modifiedTime", driveAPI, id) 144 | res, err := retryGet(client, u, 7) 145 | if err != nil { 146 | return nil, err 147 | } 148 | defer res.Body.Close() 149 | meta := &struct { 150 | ID string `json:"id"` 151 | MimeType string `json:"mimeType"` 152 | Modified time.Time `json:"modifiedTime"` 153 | }{} 154 | if err := json.NewDecoder(res.Body).Decode(meta); err != nil { 155 | return nil, err 156 | } 157 | if meta.MimeType != "application/vnd.google-apps.document" { 158 | return nil, fmt.Errorf("%s: invalid mime type: %s", id, meta.MimeType) 159 | } 160 | 161 | if res, err = retryGet(client, exportURL, 7); err != nil { 162 | return nil, err 163 | } 164 | return &Resource{ 165 | Body: res.Body, 166 | Mod: meta.Modified, 167 | Type: typeGdoc, 168 | }, nil 169 | } 170 | 171 | // retryGet tries to GET specified url up to n times. 172 | // Default client will be used if not provided. 173 | func retryGet(client *http.Client, url string, n int) (*http.Response, error) { 174 | if client == nil { 175 | client = http.DefaultClient 176 | } 177 | for i := 0; i <= n; i++ { 178 | if i > 0 { 179 | t := time.Duration((math.Pow(2, float64(i)) + rand.Float64()) * float64(time.Second)) 180 | time.Sleep(t) 181 | } 182 | res, err := client.Get(url) 183 | // return early with a good response 184 | // the rest is error handling 185 | if err == nil && res.StatusCode == http.StatusOK { 186 | return res, nil 187 | } 188 | 189 | // sometimes Drive API wouldn't even start a response, 190 | // we get net/http: TLS handshake timeout instead: 191 | // consider this a temporary failure and retry again 192 | if err != nil { 193 | continue 194 | } 195 | // otherwise, decode error response and check for "rate limit" 196 | defer res.Body.Close() 197 | var erres struct { 198 | Error struct { 199 | Errors []struct{ Reason string } 200 | } 201 | } 202 | b, _ := ioutil.ReadAll(res.Body) 203 | json.Unmarshal(b, &erres) 204 | var rateLimit bool 205 | for _, e := range erres.Error.Errors { 206 | if e.Reason == "rateLimitExceeded" || e.Reason == "userRateLimitExceeded" { 207 | rateLimit = true 208 | break 209 | } 210 | } 211 | // this is neither a rate limit error, nor a server error: 212 | // retrying is useless 213 | if !rateLimit && res.StatusCode < http.StatusInternalServerError { 214 | return nil, fmt.Errorf("fetch %s: %s; %s", url, res.Status, b) 215 | } 216 | } 217 | return nil, fmt.Errorf("%s: failed after %d retries", url, n) 218 | } 219 | 220 | func gdocID(url string) string { 221 | const s = "/document/d/" 222 | if i := strings.Index(url, s); i >= 0 { 223 | url = url[i+len(s):] 224 | } 225 | if i := strings.IndexRune(url, '/'); i > 0 { 226 | url = url[:i] 227 | } 228 | return url 229 | } 230 | 231 | func gdocExportURL(id string) string { 232 | return fmt.Sprintf("%s/files/%s/export?mimeType=text/html", driveAPI, id) 233 | } 234 | -------------------------------------------------------------------------------- /claattools/fetch_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Most of this file is heavily inspired from https://github.com/googlecodelabs/tools/blob/master/claat/fetch_test.go 16 | 17 | package claattools 18 | 19 | import ( 20 | "io/ioutil" 21 | "net/http" 22 | "net/http/httptest" 23 | "strings" 24 | "testing" 25 | ) 26 | 27 | type testTransport struct { 28 | roundTripper func(*http.Request) (*http.Response, error) 29 | } 30 | 31 | func (tt *testTransport) RoundTrip(r *http.Request) (*http.Response, error) { 32 | return tt.roundTripper(r) 33 | } 34 | 35 | func TestFetchRemote(t *testing.T) { 36 | const f = "/file.txt" 37 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 38 | if r.Method != "GET" { 39 | t.Errorf("r.Method = %q; want GET", r.Method) 40 | } 41 | if r.URL.Path != f { 42 | t.Errorf("r.URL.Path = %q; want %q", r.URL.Path, f) 43 | } 44 | w.Write([]byte("test")) 45 | })) 46 | defer ts.Close() 47 | 48 | res, err := FetchRemote(ts.URL+f, false) 49 | if err != nil { 50 | t.Fatal(err) 51 | } 52 | defer res.Body.Close() 53 | if res.Type != typeMarkdown { 54 | t.Errorf("typ = %q; want %q", res.Type, typeMarkdown) 55 | } 56 | b, _ := ioutil.ReadAll(res.Body) 57 | if s := string(b); s != "test" { 58 | t.Errorf("res = %q; want 'test'", s) 59 | } 60 | } 61 | 62 | func TestFetchRemoteDrive(t *testing.T) { 63 | const driveHost = "http://dummy" 64 | rt := &testTransport{func(r *http.Request) (*http.Response, error) { 65 | if r.Method != "GET" { 66 | t.Errorf("r.Method = %q; want GET", r.Method) 67 | } 68 | // metadata request 69 | if strings.HasSuffix(r.URL.Path, "/files/doc-123") { 70 | b := ioutil.NopCloser(strings.NewReader(`{ 71 | "mimeType": "application/vnd.google-apps.document" 72 | }`)) 73 | return &http.Response{Body: b, StatusCode: http.StatusOK}, nil 74 | } 75 | // export request 76 | if !strings.HasSuffix(r.URL.Path, "/doc-123/export") { 77 | t.Errorf("r.URL.Path = %q; want /doc-123/export suffix", r.URL.Path) 78 | } 79 | b := ioutil.NopCloser(strings.NewReader("test")) 80 | return &http.Response{Body: b, StatusCode: http.StatusOK}, nil 81 | }} 82 | clients[providerGoogle] = &http.Client{Transport: rt} 83 | 84 | res, err := FetchRemote("gdoc:doc-123", false) 85 | if err != nil { 86 | t.Fatal(err) 87 | } 88 | defer res.Body.Close() 89 | if res.Type != typeGdoc { 90 | t.Errorf("typ = %q; want %q", res.Type, typeGdoc) 91 | } 92 | b, _ := ioutil.ReadAll(res.Body) 93 | if s := string(b); s != "test" { 94 | t.Errorf("res = %q; want 'test'", s) 95 | } 96 | } 97 | 98 | func TestGdocID(t *testing.T) { 99 | tests := []struct{ in, out string }{ 100 | {"https://docs.google.com/document/d/foo", "foo"}, 101 | {"https://docs.google.com/document/d/foo/edit", "foo"}, 102 | {"https://docs.google.com/document/d/foo/edit#abc", "foo"}, 103 | {"https://docs.google.com/document/d/foo/edit?bar=baz#abc", "foo"}, 104 | {"foo", "foo"}, 105 | } 106 | for i, test := range tests { 107 | out := gdocID(test.in) 108 | if out != test.out { 109 | t.Errorf("%d: gdocID(%q) = %q; want %q", i, test.in, out, test.out) 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /claattools/nodesfilter.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Google Inc. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Some filters imported and renamed from https://github.com/googlecodelabs/tools/blob/master/export.go 16 | 17 | package claattools 18 | 19 | import "github.com/didrocks/codelab-ubuntu-tools/claat/types" 20 | 21 | // GetImageNodes filters out everything except types.NodeImage nodes, recursively. 22 | func GetImageNodes(nodes []types.Node) []*types.ImageNode { 23 | var imgs []*types.ImageNode 24 | for _, n := range nodes { 25 | switch n := n.(type) { 26 | case *types.ImageNode: 27 | imgs = append(imgs, n) 28 | case *types.ListNode: 29 | imgs = append(imgs, GetImageNodes(n.Nodes)...) 30 | case *types.ItemsListNode: 31 | for _, i := range n.Items { 32 | imgs = append(imgs, GetImageNodes(i.Nodes)...) 33 | } 34 | case *types.HeaderNode: 35 | imgs = append(imgs, GetImageNodes(n.Content.Nodes)...) 36 | case *types.URLNode: 37 | imgs = append(imgs, GetImageNodes(n.Content.Nodes)...) 38 | case *types.ButtonNode: 39 | imgs = append(imgs, GetImageNodes(n.Content.Nodes)...) 40 | case *types.InfoboxNode: 41 | imgs = append(imgs, GetImageNodes(n.Content.Nodes)...) 42 | case *types.GridNode: 43 | for _, r := range n.Rows { 44 | for _, c := range r { 45 | imgs = append(imgs, GetImageNodes(c.Content.Nodes)...) 46 | } 47 | } 48 | } 49 | } 50 | return imgs 51 | } 52 | 53 | // GetImportNodes filters out everything except types.NodeImport nodes, recursively. 54 | func GetImportNodes(nodes []types.Node) []*types.ImportNode { 55 | var imps []*types.ImportNode 56 | for _, n := range nodes { 57 | switch n := n.(type) { 58 | case *types.ImportNode: 59 | imps = append(imps, n) 60 | case *types.ListNode: 61 | imps = append(imps, GetImportNodes(n.Nodes)...) 62 | case *types.InfoboxNode: 63 | imps = append(imps, GetImportNodes(n.Content.Nodes)...) 64 | case *types.GridNode: 65 | for _, r := range n.Rows { 66 | for _, c := range r { 67 | imps = append(imps, GetImportNodes(c.Content.Nodes)...) 68 | } 69 | } 70 | } 71 | } 72 | return imps 73 | } 74 | -------------------------------------------------------------------------------- /cmd/generate/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "path" 8 | 9 | "os" 10 | 11 | "github.com/ubuntu/tutorial-deployment/apis" 12 | "github.com/ubuntu/tutorial-deployment/codelab" 13 | "github.com/ubuntu/tutorial-deployment/consts" 14 | "github.com/ubuntu/tutorial-deployment/internaltools" 15 | "github.com/ubuntu/tutorial-deployment/paths" 16 | ) 17 | 18 | func main() { 19 | flag.Usage = usage 20 | flag.Parse() 21 | args := internaltools.UniqueStrings(flag.Args()) 22 | 23 | p := paths.New() 24 | if err := p.DetectPaths(); err != nil { 25 | log.Fatalf("Couldn't detect required paths: %s", err) 26 | } 27 | if err := p.ImportTutorialPaths(args); err != nil { 28 | log.Fatalf("Couldn't load tutorial paths: %s", err) 29 | } 30 | 31 | template := path.Join(p.MetaData, consts.TemplateFileName) 32 | 33 | type result struct { 34 | c codelab.Codelab 35 | err error 36 | } 37 | ch := make(chan result) 38 | // export codelabs 39 | codelabRefs, err := codelab.Discover() 40 | if err != nil { 41 | log.Fatalf("Couldn't detect codelabs: %s", err) 42 | } 43 | if err := os.RemoveAll(p.Export); err != nil { 44 | log.Fatalf("Couldn't remove codelab export path %s: %v", p.Export, err) 45 | } 46 | for _, src := range codelabRefs { 47 | go func(ref string) { 48 | c, err := codelab.New(ref, p.Export, template, false) 49 | if err != nil { 50 | c = &codelab.Codelab{RefURI: ref} 51 | } 52 | ch <- result{*c, err} 53 | }(src) 54 | } 55 | 56 | hasError := false 57 | var codelabs []codelab.Codelab 58 | for _ = range codelabRefs { 59 | res := <-ch 60 | if res.err != nil { 61 | log.Printf("ERROR in %s: %v", res.c.RefURI, res.err) 62 | hasError = true 63 | continue 64 | } 65 | codelabs = append(codelabs, res.c) 66 | } 67 | if hasError { 68 | os.Exit(1) 69 | } 70 | 71 | if err := os.RemoveAll(p.API); err != nil { 72 | log.Fatalf("Couldn't remove API export path %s: %v", p.API, err) 73 | } 74 | dat, err := apis.GenerateContent(codelabs) 75 | if err != nil { 76 | log.Fatalf("Couldn't generate API: %s", err) 77 | } 78 | if err := apis.Save(dat); err != nil { 79 | log.Fatalf("Couldn't save API: %s", err) 80 | } 81 | } 82 | 83 | func usage() { 84 | fmt.Fprintf(os.Stderr, "Usage of %s: %s [options] [CodelabsDirOrFilesToWatch…]\n", os.Args[0], os.Args[0]) 85 | fmt.Fprintf(os.Stderr, `Generate tutorials in html, using Polymerjs and its API. 86 | 87 | It fetches in well known places the codelab list and sources (both in google 88 | doc or markdown format), the general events and categories metadata, to generate 89 | the desired output and API files. 90 | 91 | Every default directories will be detected by the tool if present in the tutorial 92 | directories. Arguments and options can tweak this behavior. 93 | 94 | `) 95 | flag.PrintDefaults() 96 | } 97 | -------------------------------------------------------------------------------- /cmd/serve/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "os" 8 | "os/signal" 9 | "path" 10 | 11 | "sync" 12 | 13 | "github.com/fsnotify/fsnotify" 14 | "github.com/ubuntu/tutorial-deployment/apis" 15 | "github.com/ubuntu/tutorial-deployment/codelab" 16 | "github.com/ubuntu/tutorial-deployment/consts" 17 | "github.com/ubuntu/tutorial-deployment/internaltools" 18 | "github.com/ubuntu/tutorial-deployment/paths" 19 | ) 20 | 21 | var codelabs []codelab.Codelab 22 | 23 | const defaultPort = 8080 24 | 25 | func main() { 26 | port := flag.Int("port", defaultPort, "Port message to listen on") 27 | flag.Usage = usage 28 | flag.Parse() 29 | args := internaltools.UniqueStrings(flag.Args()) 30 | 31 | p := paths.New() 32 | if err := p.DetectPaths(); err != nil { 33 | log.Fatalf("Couldn't detect required paths: %s", err) 34 | } 35 | if err := p.ImportTutorialPaths(args); err != nil { 36 | log.Fatalf("Couldn't load tutorial paths: %s", err) 37 | } 38 | 39 | if err := p.CreateTempOutPath(); err != nil { 40 | log.Fatalf("Couldn't create temporary export paths: %s", err) 41 | } 42 | defer func() { 43 | if err := p.CleanTempPath(); err != nil { 44 | log.Printf("Couldn't clean temporary export directory: %v\n", err) 45 | } 46 | }() 47 | 48 | var err error 49 | if watcher, err = fsnotify.NewWatcher(); err != nil { 50 | log.Fatal(err) 51 | } 52 | defer watcher.Close() 53 | 54 | template := path.Join(p.MetaData, consts.TemplateFileName) 55 | 56 | type result struct { 57 | c codelab.Codelab 58 | err error 59 | } 60 | ch := make(chan result) 61 | // export codelabs 62 | codelabRefs, err := codelab.Discover() 63 | if err != nil { 64 | log.Fatalf("Couldn't detect codelabs: %s", err) 65 | } 66 | if err := os.RemoveAll(p.Export); err != nil { 67 | log.Fatalf("Couldn't remove codelab export path %s: %v", p.Export, err) 68 | } 69 | for _, src := range codelabRefs { 70 | go func(ref string) { 71 | c, err := codelab.New(ref, p.Export, template, true) 72 | if err != nil { 73 | c = &codelab.Codelab{RefURI: ref} 74 | } 75 | ch <- result{*c, err} 76 | }(src) 77 | } 78 | 79 | hasError := false 80 | for _ = range codelabRefs { 81 | res := <-ch 82 | if res.err != nil { 83 | log.Printf("ERROR in %s: %v", res.c.RefURI, res.err) 84 | hasError = true 85 | continue 86 | } 87 | codelabs = append(codelabs, res.c) 88 | } 89 | if hasError { 90 | os.Exit(1) 91 | } 92 | 93 | if err := refreshAPIs(codelabs, p.API); err != nil { 94 | log.Fatalf("Couldn't refresh: %s", err) 95 | } 96 | 97 | // Install listeners and trigger refreshes 98 | if err := registerAllWatchers(); err != nil { 99 | log.Fatalf("Couldn't register watchers: %v", err) 100 | } 101 | wg := sync.WaitGroup{} 102 | stop := make(chan struct{}) 103 | listenForChanges(&wg, stop) 104 | 105 | startHTTPServer(*port, &wg, stop) 106 | 107 | userstop := make(chan os.Signal) 108 | signal.Notify(userstop, os.Interrupt) 109 | <-userstop 110 | 111 | close(stop) 112 | wg.Wait() 113 | } 114 | 115 | func refreshAPIs(codelabs []codelab.Codelab, apiDir string) error { 116 | if err := os.RemoveAll(apiDir); err != nil { 117 | return fmt.Errorf("Couldn't remove API export path %s: %v", apiDir, err) 118 | } 119 | dat, err := apis.GenerateContent(codelabs) 120 | if err != nil { 121 | return fmt.Errorf("Couldn't generate API: %s", err) 122 | } 123 | if err = apis.Save(dat); err != nil { 124 | return fmt.Errorf("Couldn't save API: %s", err) 125 | } 126 | return nil 127 | } 128 | 129 | func usage() { 130 | fmt.Fprintf(os.Stderr, "Usage of %s: %s [options] [CodelabsDirOrFilesToWatch…]\n", os.Args[0], os.Args[0]) 131 | fmt.Fprintf(os.Stderr, `Generate tutorials in html, using Polymerjs, to be dynamically served. 132 | 133 | Those codelabs are generated on the fly in a temporary directory and in a non 134 | destructive way. Any save on local source files (codelab markdown file or any 135 | referenced local images) will retrigger the corresponding codelab build and 136 | API generation, served by this local http webserver (default port is %d) 137 | 138 | If the currently written codelabs are out of tree, they can be specified (files or 139 | directories) directly on the command line. 140 | 141 | Every default directories will be detected by the tool if present in the tutorial 142 | directories. Arguments and options can tweak this behavior. 143 | 144 | `, defaultPort) 145 | flag.PrintDefaults() 146 | } 147 | -------------------------------------------------------------------------------- /cmd/serve/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | "path" 9 | "sync" 10 | "time" 11 | 12 | "github.com/ubuntu/tutorial-deployment/consts" 13 | "github.com/ubuntu/tutorial-deployment/paths" 14 | "github.com/ubuntu/tutorial-deployment/websocket" 15 | ) 16 | 17 | var hub = websocket.NewHub() 18 | 19 | func startHTTPServer(port int, wg *sync.WaitGroup, stop <-chan struct{}) { 20 | s := &http.Server{Addr: fmt.Sprintf(":%d", port)} 21 | log.Printf("Serving on http://localhost:%d\n", port) 22 | 23 | p := paths.New() 24 | 25 | // websocket handling 26 | http.HandleFunc("/reload", hub.NewClient) 27 | 28 | http.Handle(consts.APIURL, http.StripPrefix(consts.APIURL, http.FileServer(http.Dir(p.API)))) 29 | http.Handle(consts.ImagesURL, http.StripPrefix(consts.ImagesURL, http.FileServer(http.Dir(p.Images)))) 30 | http.Handle(consts.CodelabSrcURL, http.StripPrefix(consts.CodelabSrcURL, http.FileServer(http.Dir(p.Export)))) 31 | // always serve root file for tutorials if page refreshed 32 | http.HandleFunc(consts.ServeRootURL, func(w http.ResponseWriter, r *http.Request) { 33 | http.ServeFile(w, r, path.Join(p.Website, "index.html")) 34 | }) 35 | http.Handle("/", http.FileServer(http.Dir(p.Website))) 36 | 37 | wg.Add(3) 38 | // websocket 39 | go func() { 40 | defer wg.Done() 41 | go hub.Run() 42 | <-stop 43 | hub.Stop() 44 | }() 45 | // Serve 46 | go func() { 47 | defer wg.Done() 48 | defer s.Close() 49 | if err := s.ListenAndServe(); err != nil { 50 | log.Printf("Server quit: %s", err) 51 | } 52 | }() 53 | // Stop server 54 | go func() { 55 | defer wg.Done() 56 | <-stop 57 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 58 | if err := s.Shutdown(ctx); err != nil { 59 | panic(err) 60 | } 61 | cancel() 62 | }() 63 | 64 | } 65 | -------------------------------------------------------------------------------- /cmd/serve/watchers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "path" 6 | 7 | "sync" 8 | 9 | "fmt" 10 | 11 | "time" 12 | 13 | "github.com/fsnotify/fsnotify" 14 | "github.com/ubuntu/tutorial-deployment/codelab" 15 | "github.com/ubuntu/tutorial-deployment/internaltools" 16 | "github.com/ubuntu/tutorial-deployment/paths" 17 | ) 18 | 19 | // watchTrigger is a list of codelab to triggers when an event happen on a file 20 | type watchTrigger []*codelab.Codelab 21 | 22 | var ( 23 | watcher *fsnotify.Watcher 24 | 25 | watchedTriggers map[string]watchTrigger 26 | watchedDirs []string 27 | ) 28 | 29 | // reisterAllWatchers needs to have all watchers cleaned before up 30 | func registerAllWatchers() error { 31 | if watchedDirs != nil { 32 | log.Fatalf("Programer critical error. watchedDirs should be empty before calling registerAllWatchers. Got: %v", watchedDirs) 33 | } 34 | 35 | watchedTriggers = make(map[string]watchTrigger) 36 | for k := range codelabs { 37 | // get the reference, and not the copy for codelab 38 | c := &codelabs[k] 39 | for _, f := range c.FilesWatched { 40 | m := watchedTriggers[f] 41 | m = append(m, c) 42 | watchedTriggers[f] = m 43 | watchedDirs = append(watchedDirs, path.Dir(f)) 44 | } 45 | } 46 | watchedDirs = internaltools.UniqueStrings(watchedDirs) 47 | return watchdirs() 48 | } 49 | 50 | func listenForChanges(wg *sync.WaitGroup, stop <-chan struct{}) { 51 | wg.Add(1) 52 | go func() { 53 | defer wg.Done() 54 | defer watcher.Close() 55 | p := paths.New() 56 | for { 57 | select { 58 | case event := <-watcher.Events: 59 | if event.Op&fsnotify.Write == fsnotify.Write || 60 | event.Op&fsnotify.Remove == fsnotify.Remove || 61 | event.Op&fsnotify.Create == fsnotify.Create { 62 | // small delay because sometimes the whole source isn't flushed out to disk yet 63 | <-time.After(10 * time.Millisecond) 64 | cs := impactedCodelabs(event.Name) 65 | if err := refreshCodelabs(cs, *p); err != nil { 66 | log.Print(err) 67 | // do not send refresh signal 68 | continue 69 | } 70 | for _, c := range cs { 71 | hub.Send([]byte(c.URL)) 72 | } 73 | } 74 | 75 | case err := <-watcher.Errors: 76 | log.Println("Watch error:", err) 77 | 78 | case <-stop: 79 | return 80 | } 81 | } 82 | }() 83 | } 84 | 85 | func watchdirs() error { 86 | for _, dir := range watchedDirs { 87 | if err := watcher.Add(dir); err != nil { 88 | return err 89 | } 90 | } 91 | return nil 92 | } 93 | 94 | func refreshCodelabs(cs []*codelab.Codelab, p paths.Path) error { 95 | defer func() { 96 | if err := registerAllWatchers(); err != nil { 97 | log.Printf("Couldn't watch dirs: %v", err) 98 | } 99 | }() 100 | if err := unwatchdirs(); err != nil { 101 | return fmt.Errorf("Couldn't unwatch all dirs: %v", err) 102 | } 103 | for _, c := range cs { 104 | if err := c.Refresh(); err != nil { 105 | return fmt.Errorf("Couldn't refresh successfully %s: %v", c.RefURI, err) 106 | } 107 | } 108 | if err := refreshAPIs(codelabs, p.API); err != nil { 109 | return fmt.Errorf("Couldn't refresh: %s", err) 110 | } 111 | 112 | return nil 113 | } 114 | 115 | func impactedCodelabs(file string) []*codelab.Codelab { 116 | w, ok := watchedTriggers[file] 117 | if !ok { 118 | return nil 119 | } 120 | return []*codelab.Codelab(w) 121 | } 122 | 123 | func unwatchdirs() error { 124 | for _, dir := range watchedDirs { 125 | if err := watcher.Remove(dir); err != nil { 126 | return err 127 | } 128 | } 129 | watchedDirs = nil 130 | return nil 131 | } 132 | -------------------------------------------------------------------------------- /codelab/codelab.go: -------------------------------------------------------------------------------- 1 | package codelab 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "hash/crc64" 9 | "io/ioutil" 10 | "log" 11 | "net/http" 12 | "net/url" 13 | "os" 14 | "path" 15 | "path/filepath" 16 | "strings" 17 | 18 | "github.com/didrocks/codelab-ubuntu-tools/claat/parser" 19 | "github.com/didrocks/codelab-ubuntu-tools/claat/render" 20 | "github.com/didrocks/codelab-ubuntu-tools/claat/types" 21 | "github.com/ubuntu/tutorial-deployment/claattools" 22 | "github.com/ubuntu/tutorial-deployment/consts" 23 | 24 | // allow parsers to register themselves 25 | _ "github.com/didrocks/codelab-ubuntu-tools/claat/parser/gdoc" 26 | _ "github.com/didrocks/codelab-ubuntu-tools/claat/parser/md" 27 | ) 28 | 29 | const ( 30 | appspotPreviewURL = "https://codelabs-preview.appspot.com/?file_id=" 31 | relativeImgDir = "img" // img relative directory in codelab 32 | metaFilename = "codelab.json" 33 | ) 34 | 35 | // Codelab augments claat Codelab object by owning all Codelab Metadata and last updated time 36 | type Codelab struct { 37 | RefURI string `json:"-"` // Reference uri path 38 | types.Codelab 39 | FilesWatched []string `json:"-"` // Path to asset files to watch 40 | HideSteps *struct{} `json:"Steps,omitempty"` // Hide the Steps json export from types.Codelab with this nil object 41 | 42 | watch bool // We will need to watch files 43 | dir string // path where the codelab is stored 44 | template string // template path used 45 | } 46 | 47 | // New retrieves and parses codelab source. 48 | func New(codelabRef, dest, template string, watch bool) (*Codelab, error) { 49 | c := Codelab{ 50 | RefURI: codelabRef, 51 | template: template, 52 | watch: watch, 53 | } 54 | if err := c.download(); err != nil { 55 | return nil, err 56 | } 57 | c.dir = filepath.Join(dest, c.ID) 58 | if err := c.downloadAssets(); err != nil { 59 | return nil, err 60 | } 61 | if err := c.writeCodelab(); err != nil { 62 | return nil, err 63 | } 64 | return &c, nil 65 | } 66 | 67 | // Refresh content and assets of given codelab 68 | func (c *Codelab) Refresh() error { 69 | if err := c.wipe(); err != nil { 70 | return err 71 | } 72 | c.FilesWatched = nil 73 | if err := c.download(); err != nil { 74 | return err 75 | } 76 | if err := c.downloadAssets(); err != nil { 77 | return err 78 | } 79 | return c.writeCodelab() 80 | } 81 | 82 | // download and parse codelab content 83 | // The function will also fetch, parse and integrate its imports 84 | func (c *Codelab) download() error { 85 | res, err := claattools.Fetch(c.RefURI) 86 | if err != nil { 87 | return fmt.Errorf("failed getting: %v", err) 88 | } 89 | defer res.Body.Close() 90 | clab, err := parser.Parse(res.Type, res.Body) 91 | if err != nil { 92 | return err 93 | } 94 | 95 | // fetch imports and parse them as fragments 96 | var imports []*types.ImportNode 97 | for _, st := range clab.Steps { 98 | imports = append(imports, claattools.GetImportNodes(st.Content.Nodes)...) 99 | } 100 | ch := make(chan error, len(imports)) 101 | defer close(ch) 102 | for _, imp := range imports { 103 | go func(n *types.ImportNode) { 104 | frag, err := getFragment(n.URL) 105 | if err != nil { 106 | ch <- fmt.Errorf("%s from import: %s", n.URL, err) 107 | return 108 | } 109 | n.Content.Nodes = frag 110 | c.appendResourceToWatchFile(n.URL) 111 | ch <- nil 112 | }(imp) 113 | } 114 | for _ = range imports { 115 | if err := <-ch; err != nil { 116 | return err 117 | } 118 | } 119 | 120 | c.Codelab = *clab 121 | c.appendResourceToWatchFile(c.RefURI) 122 | return nil 123 | } 124 | 125 | var crcTable = crc64.MakeTable(crc64.ECMA) 126 | 127 | // downloadAssets get images and other assets associated to the codelab 128 | func (c *Codelab) downloadAssets() (err error) { 129 | imgDir := path.Join(c.dir, relativeImgDir) 130 | if err := os.MkdirAll(imgDir, 0755); err != nil { 131 | return err 132 | } 133 | 134 | // Handle google drive download: all images will use the same driveClient element. 135 | var client *http.Client 136 | if strings.HasPrefix(c.RefURI, consts.GdocPrefix) { 137 | client, err = claattools.DriveClient() 138 | if err != nil { 139 | return err 140 | } 141 | } 142 | 143 | type res struct { 144 | src string 145 | dest string 146 | err error 147 | } 148 | ch := make(chan res) 149 | defer close(ch) 150 | var nImages int 151 | for _, st := range c.Steps { 152 | nodes := claattools.GetImageNodes(st.Content.Nodes) 153 | nImages += len(nodes) 154 | for _, n := range nodes { 155 | go func(n *types.ImageNode) { 156 | // src can be remote or local 157 | imgURL := n.Src 158 | u, err := url.Parse(imgURL) 159 | if err != nil { 160 | ch <- res{imgURL, "", err} 161 | return 162 | } 163 | var b []byte 164 | var ext string 165 | // read (optionally download) image filename 166 | if u.Host == "" { 167 | imgURL = path.Join(path.Dir(c.RefURI), imgURL) 168 | b, err = ioutil.ReadFile(imgURL) 169 | ext = path.Ext(imgURL) 170 | } else { 171 | b, err = claattools.FetchRemoteBytes(client, imgURL, 5) 172 | ext = ".png" 173 | } 174 | if err != nil { 175 | ch <- res{imgURL, "", err} 176 | return 177 | } 178 | 179 | // compute checksum which will be new file name and write it 180 | crc := crc64.Checksum(b, crcTable) 181 | name := fmt.Sprintf("%x%s", crc, ext) 182 | n.Src = fmt.Sprintf("CODELABURL/%s/%s", relativeImgDir, name) 183 | dest := filepath.Join(imgDir, name) 184 | if err = ioutil.WriteFile(dest, b, 0644); err != nil { 185 | ch <- res{imgURL, dest, err} 186 | return 187 | } 188 | 189 | ch <- res{imgURL, dest, nil} 190 | }(n) 191 | } 192 | } 193 | 194 | // fetch possible errors 195 | var errs bytes.Buffer 196 | for i := 0; i < nImages; i++ { 197 | r := <-ch 198 | if r.err != nil { 199 | errs.WriteString(fmt.Sprintf("Couldn't copy %s => %s: %v\n", r.src, r.dest, r.err)) 200 | continue 201 | } 202 | c.appendResourceToWatchFile(r.src) 203 | } 204 | 205 | if errs.Len() > 0 { 206 | err = errors.New(errs.String()) 207 | } 208 | return err 209 | } 210 | 211 | // write codelab itself to disk: html content and json metadata 212 | func (c *Codelab) writeCodelab() error { 213 | // make sure codelab dir exists 214 | if err := os.MkdirAll(c.dir, 0755); err != nil { 215 | return err 216 | } 217 | 218 | // write metadata 219 | b, err := json.MarshalIndent(c, "", " ") 220 | if err != nil { 221 | return err 222 | } 223 | if err := ioutil.WriteFile(filepath.Join(c.dir, metaFilename), b, 0644); err != nil { 224 | return err 225 | } 226 | 227 | // main content file(s) 228 | f, err := os.Create(filepath.Join(c.dir, "index.html")) 229 | if err != nil { 230 | return err 231 | } 232 | defer f.Close() 233 | return render.Execute(f, c.template, c) 234 | } 235 | 236 | // wipe output directory content for codelab 237 | // Used when autorefreshing 238 | func (c *Codelab) wipe() error { 239 | return os.RemoveAll(c.dir) 240 | } 241 | 242 | func (c *Codelab) appendResourceToWatchFile(refPath string) error { 243 | if !c.watch { 244 | return nil 245 | } 246 | 247 | u, err := url.Parse(refPath) 248 | if err != nil { 249 | return fmt.Errorf("Couldn't parse url to append resource watch file: %s", refPath) 250 | } 251 | 252 | if u.Host == "" && strings.HasPrefix(refPath, consts.GdocPrefix) { 253 | gdocID := strings.TrimPrefix(refPath, consts.GdocPrefix) 254 | log.Printf("Can't track %s for changes as it refers to a google doc. You can head over "+ 255 | "to %s%s to preview it with a default template dynamically.", gdocID, appspotPreviewURL, gdocID) 256 | return nil 257 | } 258 | 259 | if u.Host != "" { 260 | log.Printf("%s: Can't track %s for changes as it's a remote resource. You will need to rerun this binary and "+ 261 | "refresh your page to preview the changes", c.RefURI, refPath) 262 | return nil 263 | } 264 | 265 | // don't add duplicates 266 | for _, f := range c.FilesWatched { 267 | if f == refPath { 268 | return nil 269 | } 270 | } 271 | c.FilesWatched = append(c.FilesWatched, refPath) 272 | return nil 273 | } 274 | 275 | func getFragment(url string) ([]types.Node, error) { 276 | res, err := claattools.FetchRemote(url, true) 277 | if err != nil { 278 | return nil, err 279 | } 280 | defer res.Body.Close() 281 | return parser.ParseFragment(res.Type, res.Body) 282 | } 283 | -------------------------------------------------------------------------------- /codelab/codelab_test.go: -------------------------------------------------------------------------------- 1 | package codelab 2 | 3 | import ( 4 | "bytes" 5 | "flag" 6 | "fmt" 7 | "io/ioutil" 8 | "os" 9 | "path" 10 | "path/filepath" 11 | "reflect" 12 | "sort" 13 | "strings" 14 | "testing" 15 | 16 | "github.com/ubuntu/tutorial-deployment/consts" 17 | "github.com/ubuntu/tutorial-deployment/testtools" 18 | ) 19 | 20 | var update = flag.Bool("update", false, "update generated files") 21 | 22 | func TestGenerateCodelabs(t *testing.T) { 23 | var template = "testdata/template.html" 24 | var generatedpath = "testdata/codelabgenerated" 25 | 26 | testCases := []struct { 27 | src string 28 | watch bool 29 | 30 | wantFilesWatched []string 31 | wantDiffFiles []string 32 | wantErr bool 33 | }{ 34 | {"/doesnt/exist", false, nil, nil, true}, 35 | {"testdata/codelabsrc/markdown-no-image.md", false, nil, nil, false}, 36 | {"testdata/codelabsrc/markdown-no-image.md", true, []string{"testdata/codelabsrc/markdown-no-image.md"}, nil, false}, 37 | {"testdata/codelabsrc/markdown-invalid-generated-html.md", false, nil, []string{"example-snap-tutorial/index.html"}, false}, 38 | {"testdata/codelabsrc/markdown-with-images-simple.md", false, nil, nil, false}, 39 | {"testdata/codelabsrc/markdown-with-images-simple.md", true, []string{"testdata/codelabsrc/markdown-with-images-simple.md", "testdata/codelabsrc/foo.png"}, nil, false}, 40 | {"testdata/codelabsrc/markdown-with-images-online.md", false, nil, nil, false}, 41 | {"testdata/codelabsrc/markdown-with-images-online.md", true, []string{"testdata/codelabsrc/markdown-with-images-online.md"}, nil, false}, // online images aren't tracked 42 | {"testdata/codelabsrc/markdown-with-images-relative-upper-path.md", false, nil, nil, false}, 43 | {"testdata/codelabsrc/markdown-with-images-duplicate-images.md", false, nil, nil, false}, // duplicated images have only one image 44 | {"testdata/codelabsrc/markdown-with-images-extension-preserved.md", false, nil, nil, false}, 45 | {"testdata/codelabsrc/markdown-with-images-online-jpg.md", false, nil, nil, false}, // it downloads the remote file in png 46 | {"testdata/codelabsrc/markdown-with-images.md", false, nil, nil, false}, 47 | {"testdata/codelabsrc/markdown-with-images.md", true, []string{"testdata/codelabsrc/markdown-with-images.md", "testdata/codelabsrc/baz.jpg", "testdata/codelabsrc/foo.png", "testdata/bar.png"}, nil, false}, // watch local images only 48 | {"testdata/codelabsrc/markdown-missing-image.md", false, nil, nil, true}, 49 | {"testdata/codelabsrc/markdown-modified-image.md", false, nil, nil, true}, 50 | {fmt.Sprintf("%s1XUIwNcJj0IIFtza-py5BGDUlWoNeXyO2V0XgNOQvyDQ", consts.GdocPrefix), false, nil, nil, false}, 51 | {fmt.Sprintf("%s17GGTeNbjAnnU3jNuKs9SrmQ_DhSqWJPmxxRSbWIjTiY", consts.GdocPrefix), false, nil, nil, false}, // with images 52 | {fmt.Sprintf("%s1XUIwNcJj0IIFtza-py5BGDUlWoNeXyO2V0XgNOQvyDQ", consts.GdocPrefix), true, nil, nil, false}, // no files to track 53 | {fmt.Sprintf("%s17GGTeNbjAnnU3jNuKs9SrmQ_DhSqWJPmxxRSbWIjTiY", consts.GdocPrefix), true, nil, nil, false}, // no files and images to track 54 | {fmt.Sprintf("%sinvalid", consts.GdocPrefix), false, nil, nil, true}, 55 | } 56 | for _, tc := range testCases { 57 | t.Run(fmt.Sprintf("generate %s, watch: %v", tc.src, tc.watch), func(t *testing.T) { 58 | if !*update { // we don't want update to be parallel as some tests are referencing the same source element 59 | t.Parallel() 60 | } 61 | out, teardown := tempDir(t) 62 | defer teardown() 63 | 64 | destcompare := path.Join(generatedpath, path.Base(tc.src)) 65 | 66 | // On update, override destcompare 67 | if *update { 68 | // Skip the ones where we want an error to happen or where content isn't identical 69 | if tc.wantErr || tc.wantDiffFiles != nil { 70 | return 71 | } 72 | out = destcompare 73 | if err := os.RemoveAll(out); err != nil { 74 | t.Fatalf("err: %v", err) 75 | } 76 | } 77 | 78 | c, err := New(tc.src, out, template, tc.watch) 79 | 80 | if err != nil && *update { 81 | t.Fatalf("Couldn't update %s: An error occured: %v", tc.src, err) 82 | } 83 | 84 | if (err != nil) != tc.wantErr { 85 | t.Errorf("New() error = %v, wantErr %v", err, tc.wantErr) 86 | return 87 | } 88 | // we can't continue once we get an error: c isn't valid 89 | if err != nil { 90 | return 91 | } 92 | 93 | compareAll(t, destcompare, out, tc.wantDiffFiles) 94 | 95 | sort.Strings(c.FilesWatched) 96 | sort.Strings(tc.wantFilesWatched) 97 | if !reflect.DeepEqual(c.FilesWatched, tc.wantFilesWatched) { 98 | t.Errorf("got %+v; want %+v", c.FilesWatched, tc.wantFilesWatched) 99 | } 100 | }) 101 | } 102 | } 103 | 104 | func TestRefreshCodelabs(t *testing.T) { 105 | var template = "testdata/template.html" 106 | var generatedpath = "testdata/codelabgenerated" 107 | 108 | testCases := []struct { 109 | src string 110 | watch bool 111 | 112 | wantFilesWatched []string 113 | wantDiffFiles []string 114 | wantErr bool 115 | }{ 116 | {"testdata/codelabsrc/markdown-no-image.md", false, nil, []string{"example-snap-tutorial/index.html", "example-snap-tutorial/codelab.json", "example-snap-tutorial/img/128451a661545188.png"}, false}, 117 | {"testdata/codelabsrc/markdown-no-image.md", true, []string{"testdata/codelabsrc/markdown-with-images-simple.md", "testdata/codelabsrc/foo.png"}, []string{"example-snap-tutorial/index.html", "example-snap-tutorial/codelab.json", "example-snap-tutorial/img/128451a661545188.png"}, false}, 118 | } 119 | for _, tc := range testCases { 120 | t.Run(fmt.Sprintf("refresh %s, watch: %v", tc.src, tc.watch), func(t *testing.T) { 121 | out, teardown := tempDir(t) 122 | defer teardown() 123 | 124 | compareorigin := path.Join(generatedpath, path.Base(tc.src)) 125 | 126 | // Generate content corresponding to no-image. 127 | c, err := New(tc.src, out, template, tc.watch) 128 | if err != nil { 129 | t.Fatalf("Couldn't create %s: an error occured: %v", tc.src, err) 130 | } 131 | c.RefURI = "testdata/codelabsrc/markdown-with-images-simple.md" 132 | comparenew := path.Join(generatedpath, path.Base(c.RefURI)) 133 | 134 | // Refreshing with a new markdown files containing images 135 | err = c.Refresh() 136 | 137 | if (err != nil) != tc.wantErr { 138 | t.Errorf("New() error = %v, wantErr %v", err, tc.wantErr) 139 | return 140 | } 141 | 142 | // should differ from original content and match the new content 143 | compareAll(t, compareorigin, out, tc.wantDiffFiles) 144 | compareAll(t, comparenew, out, nil) 145 | 146 | // we are watching all new source files 147 | sort.Strings(c.FilesWatched) 148 | sort.Strings(tc.wantFilesWatched) 149 | if !reflect.DeepEqual(c.FilesWatched, tc.wantFilesWatched) { 150 | t.Errorf("got %+v; want %+v", c.FilesWatched, tc.wantFilesWatched) 151 | } 152 | }) 153 | } 154 | } 155 | 156 | func tempDir(t *testing.T) (string, func()) { 157 | path, err := ioutil.TempDir("", "tutorial-test") 158 | if err != nil { 159 | t.Fatalf("err: %s", err) 160 | } 161 | return path, func() { 162 | if err := os.RemoveAll(path); err != nil { 163 | t.Fatalf("err: %s", err) 164 | } 165 | } 166 | } 167 | 168 | // compare recursively all original and generated file content 169 | func compareAll(t *testing.T, original, generated string, ignoresf []string) { 170 | var difff []string 171 | if err := filepath.Walk(original, func(f string, fi os.FileInfo, err error) error { 172 | relp := strings.TrimPrefix(f, original) 173 | // root path 174 | if relp == "" { 175 | return nil 176 | } 177 | relp = relp[1:] 178 | p := path.Join(generated, relp) 179 | 180 | // .keep files are only for keeping directory creations in remote git repo 181 | if filepath.Base(p) == ".keep" { 182 | return nil 183 | } 184 | 185 | fo, err := os.Stat(p) 186 | if err != nil { 187 | t.Fatalf("%s doesn't exist while %s does", p, f) 188 | } 189 | 190 | if fi.IsDir() { 191 | if !fo.IsDir() { 192 | t.Fatalf("%s is a directory and %s isn't", f, p) 193 | } 194 | // else, it's a directory as well and we are done. 195 | return nil 196 | } 197 | 198 | wanted, err := ioutil.ReadFile(f) 199 | if err != nil { 200 | t.Fatalf("Couldn't read %s: %v", f, err) 201 | } 202 | actual, err := ioutil.ReadFile(p) 203 | if err != nil { 204 | t.Fatalf("Couldn't read %s: %v", p, err) 205 | } 206 | if !bytes.Equal(actual, wanted) { 207 | difff = append(difff, relp) 208 | if !testtools.StringContains(ignoresf, relp) { 209 | t.Errorf("%s and %s content differs:\nACTUAL:\n%s\n\nWANTED:\n%s", p, f, actual, wanted) 210 | } 211 | } 212 | if bytes.Equal(actual, wanted) { 213 | if testtools.StringContains(ignoresf, relp) { 214 | t.Errorf("We wanted %s and %s to differ and they don't", p, f) 215 | } 216 | } 217 | return nil 218 | }); err != nil { 219 | t.Fatalf("err: %s", err) 220 | } 221 | 222 | // on the other side, check that all generated items are in origin 223 | if err := filepath.Walk(generated, func(f string, _ os.FileInfo, err error) error { 224 | relp := strings.TrimPrefix(f, generated) 225 | // root path 226 | if relp == "" { 227 | return nil 228 | } 229 | relp = relp[1:] 230 | p := path.Join(original, relp) 231 | 232 | // .keep files are only for keeping directory creations in remote git repo 233 | if filepath.Base(p) == ".keep" { 234 | return nil 235 | } 236 | 237 | if _, err := os.Stat(p); err != nil { 238 | difff = append(difff, relp) 239 | if !testtools.StringContains(ignoresf, relp) { 240 | t.Errorf("%s doesn't exist while %s does", p, f) 241 | } 242 | } 243 | return nil 244 | }); err != nil { 245 | t.Fatalf("err: %s", err) 246 | } 247 | if len(ignoresf) != len(difff) { 248 | t.Errorf("Not all expected modified files are present: want: %v, got: %v", ignoresf, difff) 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /codelab/dicover_test.go: -------------------------------------------------------------------------------- 1 | package codelab 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "testing" 7 | 8 | "github.com/ubuntu/tutorial-deployment/paths" 9 | ) 10 | 11 | func TestDiscover(t *testing.T) { 12 | testCases := []struct { 13 | tutorialPaths []string 14 | expected []string 15 | wantErr bool 16 | }{ 17 | {[]string{}, nil, false}, 18 | {[]string{"/doesnt/exist"}, nil, true}, 19 | {[]string{"testdata/nothing"}, nil, false}, 20 | {[]string{"testdata/flat"}, []string{"testdata/flat/tut1.md", "testdata/flat/tut2.md"}, false}, 21 | {[]string{"testdata/nested"}, []string{"testdata/nested/subdir1/subsub/tut1.md", "testdata/nested/subdir1/subsub/tut2.md", "testdata/nested/subdir2/tut1.md", "testdata/nested/subdir2/tut2.md"}, false}, 22 | {[]string{"testdata/flat", "testdata/flat2"}, []string{"testdata/flat/tut1.md", "testdata/flat/tut2.md", "testdata/flat2/tut1.md"}, false}, 23 | {[]string{"testdata/withgdoc"}, []string{"gdoc:mytut1", "gdoc:mytut2"}, false}, 24 | {[]string{"testdata/withgdocduplicate"}, []string{"gdoc:mytut1", "gdoc:mytut2"}, false}, 25 | {[]string{"testdata/withignored"}, []string{"testdata/withignored/tut1.md"}, false}, 26 | {[]string{"testdata/flat", "testdata/withgdoc", "testdata/withignored"}, []string{"testdata/flat/tut1.md", "testdata/flat/tut2.md", "gdoc:mytut1", "gdoc:mytut2", "testdata/withignored/tut1.md"}, false}, 27 | } 28 | for _, tc := range testCases { 29 | t.Run(fmt.Sprintf("scanning %s", tc.tutorialPaths), func(t *testing.T) { 30 | // Setup/Teardown 31 | p, teardown := paths.MockPath() 32 | defer teardown() 33 | p.TutorialInputs = tc.tutorialPaths 34 | 35 | // Test 36 | tutorials, err := Discover() 37 | 38 | if (err != nil) != tc.wantErr { 39 | t.Errorf("Discover() error = %v, wantErr %v", err, tc.wantErr) 40 | return 41 | } 42 | if !reflect.DeepEqual(tutorials, tc.expected) { 43 | t.Errorf("got %+v; want %+v", tutorials, tc.expected) 44 | } 45 | }) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /codelab/discover.go: -------------------------------------------------------------------------------- 1 | package codelab 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "os" 7 | "path/filepath" 8 | 9 | "strings" 10 | 11 | "path" 12 | 13 | "github.com/ubuntu/tutorial-deployment/consts" 14 | "github.com/ubuntu/tutorial-deployment/internaltools" 15 | "github.com/ubuntu/tutorial-deployment/paths" 16 | ) 17 | 18 | const ( 19 | gdocFileName = "gdoc.def" 20 | ) 21 | 22 | // Discover existing codelabs in the import path 23 | func Discover() (codelabs []string, err error) { 24 | p := paths.New() 25 | for _, fpath := range p.TutorialInputs { 26 | fi, err := os.Stat(fpath) 27 | if err != nil { 28 | return nil, fmt.Errorf("Couldn't stat: %s", err) 29 | } 30 | if fi.IsDir() { 31 | err = filepath.Walk(fpath, func(fpath string, i os.FileInfo, err error) error { 32 | if err != nil { 33 | return err 34 | } 35 | if !i.IsDir() { 36 | newCodelabs, err := getCodelabReference(fpath) 37 | if err != nil { 38 | return err 39 | } 40 | codelabs = append(codelabs, newCodelabs...) 41 | } 42 | return nil 43 | }) 44 | if err != nil { 45 | return nil, err 46 | } 47 | } else { 48 | newCodelabs, err := getCodelabReference(fpath) 49 | if err != nil { 50 | return nil, err 51 | } 52 | codelabs = append(codelabs, newCodelabs...) 53 | } 54 | } 55 | codelabs = internaltools.UniqueStrings(codelabs) 56 | 57 | return codelabs, nil 58 | } 59 | 60 | // return a list of file paths itself or gdoc: prefix. The file path will be a list of one element for markdown 61 | // files and the number of gdoc elements in the gdoc file 62 | // we ignore any file starting with _ and not ending up with .md 63 | // nor being gdoc.def files (handling google doc definition files) 64 | // those could be images or other assets. 65 | func getCodelabReference(p string) (r []string, err error) { 66 | if strings.HasPrefix(path.Base(p), "_") { 67 | return nil, nil 68 | } 69 | 70 | if strings.HasSuffix(p, ".md") { 71 | return []string{p}, nil 72 | } 73 | if path.Base(p) != gdocFileName { 74 | return nil, nil 75 | } 76 | 77 | // open the gdoc definition file and pass references back 78 | f, err := os.Open(p) 79 | if err != nil { 80 | return nil, fmt.Errorf("Couldn't open %s: %v", p, err) 81 | } 82 | defer f.Close() 83 | 84 | s := bufio.NewScanner(f) 85 | for s.Scan() { 86 | l := strings.Trim(s.Text(), " ") 87 | if strings.HasPrefix(l, "#") || len(l) == 0 { 88 | continue 89 | } 90 | r = append(r, fmt.Sprintf("%s%s", consts.GdocPrefix, l)) 91 | } 92 | if err := s.Err(); err != nil { 93 | return nil, fmt.Errorf("Couldn't read %s: %v", p, err) 94 | } 95 | 96 | return r, nil 97 | } 98 | -------------------------------------------------------------------------------- /codelab/testdata/bar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/bar.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/gdoc:17GGTeNbjAnnU3jNuKs9SrmQ_DhSqWJPmxxRSbWIjTiY/basic-snap-usage/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "basic-snap-usage", 3 | "duration": 10, 4 | "title": "Basic snap usage", 5 | "summary": "In this tutorial, we are going to cover the very basic on how to use snaps on your distributions, and the main benefits from them.", 6 | "theme": "snap", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snap" 12 | ], 13 | "tags": [ 14 | "beginner", 15 | "idf-2016", 16 | "snap", 17 | "usage" 18 | ], 19 | "feedback": "https://github.com/ubuntu/codelabs/issues", 20 | "difficulty": 1, 21 | "published": "1983-09-13T00:00:01Z", 22 | "url": "basic-snap-usage" 23 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/gdoc:17GGTeNbjAnnU3jNuKs9SrmQ_DhSqWJPmxxRSbWIjTiY/basic-snap-usage/img/17e5009256674631.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/gdoc:17GGTeNbjAnnU3jNuKs9SrmQ_DhSqWJPmxxRSbWIjTiY/basic-snap-usage/img/17e5009256674631.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/gdoc:17GGTeNbjAnnU3jNuKs9SrmQ_DhSqWJPmxxRSbWIjTiY/basic-snap-usage/img/f9f287c2e1980df1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/gdoc:17GGTeNbjAnnU3jNuKs9SrmQ_DhSqWJPmxxRSbWIjTiY/basic-snap-usage/img/f9f287c2e1980df1.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/gdoc:17GGTeNbjAnnU3jNuKs9SrmQ_DhSqWJPmxxRSbWIjTiY/basic-snap-usage/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 |

Welcome to the world of snaps! In this tutorial, we are going to cover the very basics on how to use snaps on your Linux distribution, and you'll directly see the main benefits of them in action.

11 |

12 |

What you'll learn

13 |
    14 |
  • How to install the snapd service on your system.
  • 15 |
  • How to search for software.
  • 16 |
  • How to check the list of installed pieces of software.
  • 17 |
  • How snaps are updated.
  • 18 |
  • What snap channels are and how to use them.
  • 19 |
  • How to roll back to the previous version of a snap.
  • 20 |
21 |

If this looks like a long list to you, you will find that you are going to get through it in a breeze. All of the above is very easy to do thanks to the simplicity of the snap command line interface.

22 |

What you'll need

23 |
    24 |
  • Any supported GNU/Linux distribution (see next step of the tutorial for more details).
  • 25 |
  • Some very basic knowledge of command line use.
  • 26 |
27 |

This tutorial is focused on using the snap command. Some command line tools are provided for you to simply copy and paste.

28 | 29 |

How will you use this tutorial?

30 | 31 | Only read through it 32 | Read it and complete the exercises 33 | 34 |

What is your current level of experience working with snap?

35 | 36 | Novice 37 | Intermediate 38 | Proficient 39 | 40 |
41 | 42 | 43 |
44 | 45 | 46 |

Installing snapd

47 |

snapd is the service which runs on your machine and keeps track of your installed snaps, interacts with the store and provides the snap command for you to interact with it. Installing it on any of the Linux distributions mentioned below is straight-forward.

48 |

49 |

Different distributions:

50 |

Arch

51 |
$ sudo pacman -S snapd
 52 | 
 53 | # enable the snapd systemd service:
 54 | sudo systemctl enable --now snapd.socket
55 |

Debian (Sid only)

56 |
$ sudo apt install snapd
57 |

Fedora

58 |
$ sudo dnf copr enable zyga/snapcore
 59 | $ sudo dnf install snapd
 60 | 
 61 | # enable the snapd systemd service:
 62 | $ sudo systemctl enable --now snapd.service
 63 | 
 64 | # SELinux support is in beta, so currently:
 65 | $ sudo setenforce 0
 66 | 
 67 | # to persist, edit /etc/selinux/config to set SELINUX=permissive and reboot.
68 |

Gentoo

69 |

Install the gentoo-snappy overlay.

70 |

OpenEmbedded/Yocto

71 |

Install the snap meta layer.

72 |

openSuSE

73 |
$ sudo zypper addrepo http://download.opensuse.org/repositories/system:/snappy/openSUSE_Leap_42.2/ snappy
 74 | $ sudo zypper install snapd
75 |

OpenWrt

76 |

Enable the snap-openwrt feed.

77 |

Ubuntu

78 |

You should already be all set on ubuntu 16.04 LTS desktop. On 14.04, you need to install it though via:

79 |
$ sudo apt install snapd
80 |

Now that your system is all ready to go, let's install your first snap on it!

81 | 83 | 84 | 85 |
86 | 87 | 88 |

Searching for a snap

89 |

snapd is up and running now, so let's start using it! Here is how you can find any "hello world" kind of snaps in the store:

90 |
$ snap find hello
 91 | hello-node-snap       1.0.2        bhdouglass      -          A simple hello world command
 92 | hello-mdeslaur        2.10         mdeslaur        -          GNU Hello, the "hello world" snap
 93 | hello-snap            0.01         muhammad        -          GNU hello-snap, the "Hello, Snap!" snap
 94 | hello                 2.10         canonical       -          GNU Hello, the "hello world" snap
 95 | hello-world           6.3          canonical       -          The 'hello-world' of snaps
 96 | hello-sergiusens      1.0          sergiusens      -          hello world example
 97 | hello-gabriell        0.1          gabriell        -          Qt Hello World example
 98 | hello-bluet           0.1          bluet           -          Qt Hello World example
 99 | so-hello-world        0.2          shadowen        -          the old classic
100 | hello-huge            1.0          noise           -          a really big snap
101 |

snap find <search terms> will query the store and list the results with their version number, developer names and description.

102 |

Install and execution

103 |

As you can see, a number of developers uploaded snaps related to "hello world". Let's just install one of them.

104 |
$ sudo snap install hello
105 | 
106 | hello (stable) 2.10 from 'canonical' installed
107 | 109 |

To run the command, simply type hello in the command line (which is a command provided by the hello snap:

110 |
$ hello
111 | Hello, world!
112 |

This is obviously just a simple example, what it has in common with all other snaps though, is that it runs fully confined and can only access its own data.

113 |

Check which snaps are installed

114 |

See the snaps installed on your system with snap list, which will also tell you the software version, the unique revision, the developer of the installed snap, and any optional extra information.

115 |
$ snap list
116 | Name                     Version        Rev  Developer   Notes
117 | hello                    2.10           20   canonical   -
118 | core              16.04.1        423  canonical   -
119 |

You will note that the core snap, containing the base snap system is also part of the list. Among other things, it includes a newer snapd, which will make sure you will always be up to date).

120 |

Keeping your system up to date

121 |

The good news is that snaps are updated automatically in the background every day! If you want, you can still get the latest version of all your snaps manually by running snap refresh. It will bring you completely up to date for all snaps, unless you specify a particular snap to refresh.

122 |
$ sudo snap refresh hello
123 | error: cannot refresh "hello": snap "hello" has no updates available
124 | $ sudo snap refresh
125 | core updated
126 | hello 64.75 MB [=====================================>___]   12s
127 | 
128 |

But these aren't the only features of the snap command: you can get way more fine-grained in terms of tracking various versions of the same app, depending on how close to current development you want to be. This is all possible thanks to the channel feature! We might delve into this later on.

129 | 130 | 131 |
132 | 133 | 134 |

Snap can ship one or more commands

135 |

Our first example was simple and shipped only one command, but in general snap packages can contain more than one command (for example a set of tools shipped in one snap). All commands are then namespaced by the snap package name. Run the steps below to see an example in action:

136 |
$ sudo snap install hello-world
137 | 0 B / 20.00 KB [_______________________________________________________] 0.00 %
138 | 
139 | hello-world (stable) 6.3 from 'canonical' installed
140 | $ hello-world
141 | Hello World!
142 | $ hello-world.env
143 | < env variables >
144 | 146 |

Snap can also host services

147 |

What is a service? A service is simply a long running command, which will ideally always be on or for a definite period of time to answer some requests.

148 |

Snaps can also ship system-wide services. If you install the snap package called shout (a self-contained web irc client), you can see this live in action - simply point your browser to http://localhost:9000/ to interact with the service.

149 |

Services of snaps are simply started/stopped on system startup and shutdown. They can be configured to be activated on demand as well.

150 |

Removing a snap

151 |

Removing a snap is just a command away, all you need to do is run snap remove <snap name>. In our case just do:

152 |
$ sudo snap remove hello-world
153 | 
154 | hello-world removed
155 |

Nice and clean, nothing is left-over! Application code, its run time dependencies and associated user data are all cleaned up. If your snap declared a service, they will as well be shut down and removed.

156 | 157 | 158 |
159 | 160 | 161 |

Developers can release stable, candidate, beta and edge versions of a snap at the same time, to engage with a community who are willing to test upcoming changes. You decide how close to the leading edge you want to be.

162 |

By default, snaps are installed from the stable channel. By convention, developers use the candidate channel to provide a heads-up of a new stable revision, putting it in candidate a few days before stable so that people can test it out. The beta channel is for unfinished but interesting milestones, and the edge channel is conventionally used for regular or daily development builds that have passed some lightweight smoke-testing.

163 |

Switching channel for installed apps

164 |
$ sudo snap refresh hello --channel=beta
165 | 
166 | hello (beta) 2.10.1 from 'canonical' refreshed
167 |

Now, you can run the beta version of the snap and see its output is different:

168 |
$ hello
169 | Hello, snap padawan!
170 |

snapd will now track the beta channel of the hello snap and get any updates delivered through it.

171 | 174 |

And revert if something goes wrong!

175 |

One of the features of snapd is to be able to simply roll back to a previous version of an application (including the data associated with the snap) for any reason:

176 |
$ sudo snap revert hello
177 | 
178 | hello reverted to 2.10
179 | $ hello
180 | Hello, world!
181 |

With this rollback system built-in, you can confidently update knowing that you will always have a way to go back to the previous working state!

182 | 183 | 184 |
185 | 186 | 187 |

Easy, wasn't it?

188 |

Congratulations! You made it!

189 |

By now you should have found snaps in the store, installed and updated them, changed between channels and much more. The snap command line is designed to be as simple and memorisable as possible. After using it just a couple of times, it should become second nature to you.

190 |

Next steps

191 |
    192 |
  • Jump into more advanced features and techniques of snaps, by reading the exhaustive "Advanced snap usage" tutorial.
  • 193 |
  • Be amazed by the ease of creating a snap for your project by following the snapcraft tutorial called "Creating your first snap".
  • 194 |
  • Join the snapcraft.io community by subscribing to our mailing list.
  • 195 |
196 |

Further readings

197 | 201 | 202 | 203 |
204 | 205 |
206 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/gdoc:1XUIwNcJj0IIFtza-py5BGDUlWoNeXyO2V0XgNOQvyDQ/basic-snap-usage/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "basic-snap-usage", 3 | "duration": 10, 4 | "title": "Basic snap usage", 5 | "summary": "In this tutorial, we are going to cover the very basic on how to use snaps on your distributions, and the main benefits from them.", 6 | "theme": "snap", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snap" 12 | ], 13 | "tags": [ 14 | "beginner", 15 | "idf-2016", 16 | "snap", 17 | "usage" 18 | ], 19 | "feedback": "https://github.com/ubuntu/codelabs/issues", 20 | "difficulty": 1, 21 | "published": "1984-04-22T00:00:01Z", 22 | "url": "basic-snap-usage" 23 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/gdoc:1XUIwNcJj0IIFtza-py5BGDUlWoNeXyO2V0XgNOQvyDQ/basic-snap-usage/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 |

Welcome to the world of snaps! In this tutorial, we are going to cover the very basics on how to use snaps on your Linux distribution, and you'll directly see the main benefits of them in action.

11 |

What you'll learn

12 |
    13 |
  • How to install the snapd service on your system.
  • 14 |
  • How to search for software.
  • 15 |
  • How to check the list of installed pieces of software.
  • 16 |
  • How snaps are updated.
  • 17 |
  • What snap channels are and how to use them.
  • 18 |
  • How to roll back to the previous version of a snap.
  • 19 |
20 |

If this looks like a long list to you, you will find that you are going to get through it in a breeze. All of the above is very easy to do thanks to the simplicity of the snap command line interface.

21 |

What you'll need

22 |
    23 |
  • Any supported GNU/Linux distribution (see next step of the tutorial for more details).
  • 24 |
  • Some very basic knowledge of command line use.
  • 25 |
26 |

This tutorial is focused on using the snap command. Some command line tools are provided for you to simply copy and paste.

27 | 28 |

How will you use this tutorial?

29 | 30 | Only read through it 31 | Read it and complete the exercises 32 | 33 |

What is your current level of experience working with snap?

34 | 35 | Novice 36 | Intermediate 37 | Proficient 38 | 39 |
40 | 41 | 42 |
43 | 44 | 45 |

Installing snapd

46 |

snapd is the service which runs on your machine and keeps track of your installed snaps, interacts with the store and provides the snap command for you to interact with it. Installing it on any of the Linux distributions mentioned below is straight-forward.

47 |

Different distributions:

48 |

Arch

49 |
$ sudo pacman -S snapd
 50 | 
 51 | # enable the snapd systemd service:
 52 | sudo systemctl enable --now snapd.socket
53 |

Debian (Sid only)

54 |
$ sudo apt install snapd
55 |

Fedora

56 |
$ sudo dnf copr enable zyga/snapcore
 57 | $ sudo dnf install snapd
 58 | 
 59 | # enable the snapd systemd service:
 60 | $ sudo systemctl enable --now snapd.service
 61 | 
 62 | # SELinux support is in beta, so currently:
 63 | $ sudo setenforce 0
 64 | 
 65 | # to persist, edit /etc/selinux/config to set SELINUX=permissive and reboot.
66 |

Gentoo

67 |

Install the gentoo-snappy overlay.

68 |

OpenEmbedded/Yocto

69 |

Install the snap meta layer.

70 |

openSuSE

71 |
$ sudo zypper addrepo http://download.opensuse.org/repositories/system:/snappy/openSUSE_Leap_42.2/ snappy
 72 | $ sudo zypper install snapd
73 |

OpenWrt

74 |

Enable the snap-openwrt feed.

75 |

Ubuntu

76 |

You should already be all set on ubuntu 16.04 LTS desktop. On 14.04, you need to install it though via:

77 |
$ sudo apt install snapd
78 |

Now that your system is all ready to go, let's install your first snap on it!

79 | 81 | 82 | 83 |
84 | 85 | 86 |

Searching for a snap

87 |

snapd is up and running now, so let's start using it! Here is how you can find any "hello world" kind of snaps in the store:

88 |
$ snap find hello
 89 | hello-node-snap       1.0.2        bhdouglass      -          A simple hello world command
 90 | hello-mdeslaur        2.10         mdeslaur        -          GNU Hello, the "hello world" snap
 91 | hello-snap            0.01         muhammad        -          GNU hello-snap, the "Hello, Snap!" snap
 92 | hello                 2.10         canonical       -          GNU Hello, the "hello world" snap
 93 | hello-world           6.3          canonical       -          The 'hello-world' of snaps
 94 | hello-sergiusens      1.0          sergiusens      -          hello world example
 95 | hello-gabriell        0.1          gabriell        -          Qt Hello World example
 96 | hello-bluet           0.1          bluet           -          Qt Hello World example
 97 | so-hello-world        0.2          shadowen        -          the old classic
 98 | hello-huge            1.0          noise           -          a really big snap
99 |

snap find <search terms> will query the store and list the results with their version number, developer names and description.

100 |

Install and execution

101 |

As you can see, a number of developers uploaded snaps related to "hello world". Let's just install one of them.

102 |
$ sudo snap install hello
103 | 
104 | hello (stable) 2.10 from 'canonical' installed
105 | 107 |

To run the command, simply type hello in the command line (which is a command provided by the hello snap:

108 |
$ hello
109 | Hello, world!
110 |

This is obviously just a simple example, what it has in common with all other snaps though, is that it runs fully confined and can only access its own data.

111 |

Check which snaps are installed

112 |

See the snaps installed on your system with snap list, which will also tell you the software version, the unique revision, the developer of the installed snap, and any optional extra information.

113 |
$ snap list
114 | Name                     Version        Rev  Developer   Notes
115 | hello                    2.10           20   canonical   -
116 | core              16.04.1        423  canonical   -
117 |

You will note that the core snap, containing the base snap system is also part of the list. Among other things, it includes a newer snapd, which will make sure you will always be up to date).

118 |

Keeping your system up to date

119 |

The good news is that snaps are updated automatically in the background every day! If you want, you can still get the latest version of all your snaps manually by running snap refresh. It will bring you completely up to date for all snaps, unless you specify a particular snap to refresh.

120 |
$ sudo snap refresh hello
121 | error: cannot refresh "hello": snap "hello" has no updates available
122 | $ sudo snap refresh
123 | core updated
124 | hello 64.75 MB [=====================================>___]   12s
125 | 
126 |

But these aren't the only features of the snap command: you can get way more fine-grained in terms of tracking various versions of the same app, depending on how close to current development you want to be. This is all possible thanks to the channel feature! We might delve into this later on.

127 | 128 | 129 |
130 | 131 | 132 |

Snap can ship one or more commands

133 |

Our first example was simple and shipped only one command, but in general snap packages can contain more than one command (for example a set of tools shipped in one snap). All commands are then namespaced by the snap package name. Run the steps below to see an example in action:

134 |
$ sudo snap install hello-world
135 | 0 B / 20.00 KB [_______________________________________________________] 0.00 %
136 | 
137 | hello-world (stable) 6.3 from 'canonical' installed
138 | $ hello-world
139 | Hello World!
140 | $ hello-world.env
141 | < env variables >
142 | 144 |

Snap can also host services

145 |

What is a service? A service is simply a long running command, which will ideally always be on or for a definite period of time to answer some requests.

146 |

Snaps can also ship system-wide services. If you install the snap package called shout (a self-contained web irc client), you can see this live in action - simply point your browser to http://localhost:9000/ to interact with the service.

147 |

Services of snaps are simply started/stopped on system startup and shutdown. They can be configured to be activated on demand as well.

148 |

Removing a snap

149 |

Removing a snap is just a command away, all you need to do is run snap remove <snap name>. In our case just do:

150 |
$ sudo snap remove hello-world
151 | 
152 | hello-world removed
153 |

Nice and clean, nothing is left-over! Application code, its run time dependencies and associated user data are all cleaned up. If your snap declared a service, they will as well be shut down and removed.

154 | 155 | 156 |
157 | 158 | 159 |

Developers can release stable, candidate, beta and edge versions of a snap at the same time, to engage with a community who are willing to test upcoming changes. You decide how close to the leading edge you want to be.

160 |

By default, snaps are installed from the stable channel. By convention, developers use the candidate channel to provide a heads-up of a new stable revision, putting it in candidate a few days before stable so that people can test it out. The beta channel is for unfinished but interesting milestones, and the edge channel is conventionally used for regular or daily development builds that have passed some lightweight smoke-testing.

161 |

Switching channel for installed apps

162 |
$ sudo snap refresh hello --channel=beta
163 | 
164 | hello (beta) 2.10.1 from 'canonical' refreshed
165 |

Now, you can run the beta version of the snap and see its output is different:

166 |
$ hello
167 | Hello, snap padawan!
168 |

snapd will now track the beta channel of the hello snap and get any updates delivered through it.

169 | 172 |

And revert if something goes wrong!

173 |

One of the features of snapd is to be able to simply roll back to a previous version of an application (including the data associated with the snap) for any reason:

174 |
$ sudo snap revert hello
175 | 
176 | hello reverted to 2.10
177 | $ hello
178 | Hello, world!
179 |

With this rollback system built-in, you can confidently update knowing that you will always have a way to go back to the previous working state!

180 | 181 | 182 |
183 | 184 | 185 |

Easy, wasn't it?

186 |

Congratulations! You made it!

187 |

By now you should have found snaps in the store, installed and updated them, changed between channels and much more. The snap command line is designed to be as simple and memorisable as possible. After using it just a couple of times, it should become second nature to you.

188 |

Next steps

189 |
    190 |
  • Jump into more advanced features and techniques of snaps, by reading the exhaustive "Advanced snap usage" tutorial.
  • 191 |
  • Be amazed by the ease of creating a snap for your project by following the snapcraft tutorial called "Creating your first snap".
  • 192 |
  • Join the snapcraft.io community by subscribing to our mailing list.
  • 193 |
194 |

Further readings

195 | 199 | 200 | 201 |
202 | 203 |
204 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-invalid-generated-html.md/example-snap-tutorial/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "example-snap-tutorial", 3 | "duration": 6, 4 | "title": "Example snap tutorial", 5 | "summary": "This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words", 6 | "theme": "", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snapcraft" 12 | ], 13 | "tags": [ 14 | "interfaces", 15 | "content-interfaces", 16 | "up-to-four" 17 | ], 18 | "feedback": "http://Link", 19 | "difficulty": 2, 20 | "url": "example-snap-tutorial", 21 | "updated": "2017-04-04T14:25:51+02:00" 22 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-invalid-generated-html.md/example-snap-tutorial/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 | First step simple content 11 | 12 | 13 | 14 | 15 | At the top, you saw some medata, here are additional notes to them:
    16 |
  • Id would be used for url (tutorial/
  • 17 |
  • Title is 5 years max
  • 18 |
  • Status: either Published or Draft
  • 19 |
20 | REPLACED CONTENT 21 | 22 | category, corresponding to one of the area of the developer site 23 | 24 |
25 | 26 | 27 | This is the last step 28 | 29 | 30 | 31 |
32 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-modified-image.md/example-snap-tutorial/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "example-snap-tutorial", 3 | "duration": 6, 4 | "title": "Example snap tutorial", 5 | "summary": "This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words", 6 | "theme": "", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snapcraft" 12 | ], 13 | "tags": [ 14 | "interfaces", 15 | "content-interfaces", 16 | "up-to-four" 17 | ], 18 | "feedback": "http://Link", 19 | "difficulty": 2, 20 | "url": "example-snap-tutorial", 21 | "updated": "2017-04-05T08:59:49+02:00" 22 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-modified-image.md/example-snap-tutorial/img/128451a661545188.png: -------------------------------------------------------------------------------- 1 | Invalid image content 2 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-modified-image.md/example-snap-tutorial/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 | A, local image 11 | 12 | 13 | 14 | 15 | At the top, you saw some medata, here are additional notes to them:
    16 |
  • Id would be used for url (tutorial/
  • 17 |
  • Title is 5 years max
  • 18 |
  • Status: either Published or Draft
  • 19 |
20 | 21 | 22 | category, corresponding to one of the area of the developer site 23 | 24 |
25 | 26 | 27 | This is the last step 28 | 29 | 30 | 31 |
32 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-no-image.md/example-snap-tutorial/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "example-snap-tutorial", 3 | "duration": 6, 4 | "title": "Example snap tutorial", 5 | "summary": "This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words", 6 | "theme": "", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snapcraft" 12 | ], 13 | "tags": [ 14 | "content-interfaces", 15 | "interfaces", 16 | "up-to-four" 17 | ], 18 | "feedback": "http://Link", 19 | "difficulty": 1, 20 | "published": "2017-01-13T00:00:01Z", 21 | "url": "example-snap-tutorial" 22 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-no-image.md/example-snap-tutorial/img/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-no-image.md/example-snap-tutorial/img/.keep -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-no-image.md/example-snap-tutorial/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 |

First step simple content

11 | 12 | 13 |
14 | 15 | 16 |

At the top, you saw some medata, here are additional notes to them:

17 |
    18 |
  • Id would be used for url (tutorial/)
  • 19 |
  • Title is 5 years max
  • 20 |
  • Status: either Published or Draft
  • 21 |
22 | 24 | 26 |

category, corresponding to one of the area of the developer site

27 | 28 | 29 |
30 | 31 | 32 |

This is the last step

33 | 34 | 35 |
36 | 37 |
38 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-duplicate-images.md/example-snap-tutorial/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "example-snap-tutorial", 3 | "duration": 6, 4 | "title": "Example snap tutorial", 5 | "summary": "This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words", 6 | "theme": "", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snapcraft" 12 | ], 13 | "tags": [ 14 | "content-interfaces", 15 | "interfaces", 16 | "up-to-four" 17 | ], 18 | "feedback": "http://Link", 19 | "difficulty": 2, 20 | "published": "2017-01-13T00:00:01Z", 21 | "url": "example-snap-tutorial" 22 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-duplicate-images.md/example-snap-tutorial/img/128451a661545188.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images-duplicate-images.md/example-snap-tutorial/img/128451a661545188.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-duplicate-images.md/example-snap-tutorial/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 |

A, local image

11 |

12 |

A relative image, in upper directory

13 |

14 | 15 | 16 |
17 | 18 | 19 |

At the top, you saw some medata, here are additional notes to them:

20 |
    21 |
  • Id would be used for url (tutorial/)
  • 22 |
  • Title is 5 years max
  • 23 |
  • Status: either Published or Draft
  • 24 |
25 | 27 | 29 |

category, corresponding to one of the area of the developer site

30 | 31 | 32 |
33 | 34 | 35 |

This is the last step

36 | 37 | 38 |
39 | 40 |
41 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-extension-preserved.md/example-snap-tutorial/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "example-snap-tutorial", 3 | "duration": 6, 4 | "title": "Example snap tutorial", 5 | "summary": "This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words", 6 | "theme": "", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snapcraft" 12 | ], 13 | "tags": [ 14 | "content-interfaces", 15 | "interfaces", 16 | "up-to-four" 17 | ], 18 | "feedback": "http://Link", 19 | "difficulty": 2, 20 | "published": "2017-01-13T00:00:01Z", 21 | "url": "example-snap-tutorial" 22 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-extension-preserved.md/example-snap-tutorial/img/128451a661545188.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images-extension-preserved.md/example-snap-tutorial/img/128451a661545188.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-extension-preserved.md/example-snap-tutorial/img/38e08f189734d781.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images-extension-preserved.md/example-snap-tutorial/img/38e08f189734d781.jpg -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-extension-preserved.md/example-snap-tutorial/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 |

A local image

11 |

12 |

Extensions are kept

13 |

14 | 15 | 16 |
17 | 18 | 19 |

At the top, you saw some medata, here are additional notes to them:

20 |
    21 |
  • Id would be used for url (tutorial/)
  • 22 |
  • Title is 5 years max
  • 23 |
  • Status: either Published or Draft
  • 24 |
25 | 27 | 29 |

category, corresponding to one of the area of the developer site

30 | 31 | 32 |
33 | 34 | 35 |

This is the last step

36 | 37 | 38 |
39 | 40 |
41 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-online-jpg.md/example-snap-tutorial/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "example-snap-tutorial", 3 | "duration": 6, 4 | "title": "Example snap tutorial", 5 | "summary": "This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words", 6 | "theme": "", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snapcraft" 12 | ], 13 | "tags": [ 14 | "content-interfaces", 15 | "interfaces", 16 | "up-to-four" 17 | ], 18 | "feedback": "http://Link", 19 | "difficulty": 2, 20 | "published": "2017-01-13T00:00:01Z", 21 | "url": "example-snap-tutorial" 22 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-online-jpg.md/example-snap-tutorial/img/38e08f189734d781.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images-online-jpg.md/example-snap-tutorial/img/38e08f189734d781.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-online-jpg.md/example-snap-tutorial/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 |

A remote image in jpg

11 |

12 | 13 | 14 |
15 | 16 | 17 |

At the top, you saw some medata, here are additional notes to them:

18 |
    19 |
  • Id would be used for url (tutorial/)
  • 20 |
  • Title is 5 years max
  • 21 |
  • Status: either Published or Draft
  • 22 |
23 | 25 | 27 |

category, corresponding to one of the area of the developer site

28 | 29 | 30 |
31 | 32 | 33 |

This is the last step

34 | 35 | 36 |
37 | 38 |
39 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-online.md/example-snap-tutorial/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "example-snap-tutorial", 3 | "duration": 6, 4 | "title": "Example snap tutorial", 5 | "summary": "This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words", 6 | "theme": "", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snapcraft" 12 | ], 13 | "tags": [ 14 | "content-interfaces", 15 | "interfaces", 16 | "up-to-four" 17 | ], 18 | "feedback": "http://Link", 19 | "difficulty": 2, 20 | "published": "2017-01-13T00:00:01Z", 21 | "url": "example-snap-tutorial" 22 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-online.md/example-snap-tutorial/img/9d4087c57696f1bc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images-online.md/example-snap-tutorial/img/9d4087c57696f1bc.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-online.md/example-snap-tutorial/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 |

A remote image

11 |

12 | 13 | 14 |
15 | 16 | 17 |

At the top, you saw some medata, here are additional notes to them:

18 |
    19 |
  • Id would be used for url (tutorial/)
  • 20 |
  • Title is 5 years max
  • 21 |
  • Status: either Published or Draft
  • 22 |
23 | 25 | 27 |

category, corresponding to one of the area of the developer site

28 | 29 | 30 |
31 | 32 | 33 |

This is the last step

34 | 35 | 36 |
37 | 38 |
39 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-relative-upper-path.md/example-snap-tutorial/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "example-snap-tutorial", 3 | "duration": 6, 4 | "title": "Example snap tutorial", 5 | "summary": "This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words", 6 | "theme": "", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snapcraft" 12 | ], 13 | "tags": [ 14 | "content-interfaces", 15 | "interfaces", 16 | "up-to-four" 17 | ], 18 | "feedback": "http://Link", 19 | "difficulty": 2, 20 | "published": "2017-01-13T00:00:01Z", 21 | "url": "example-snap-tutorial" 22 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-relative-upper-path.md/example-snap-tutorial/img/128451a661545188.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images-relative-upper-path.md/example-snap-tutorial/img/128451a661545188.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-relative-upper-path.md/example-snap-tutorial/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 |

A relative image, in upper directory

11 |

12 | 13 | 14 |
15 | 16 | 17 |

At the top, you saw some medata, here are additional notes to them:

18 |
    19 |
  • Id would be used for url (tutorial/)
  • 20 |
  • Title is 5 years max
  • 21 |
  • Status: either Published or Draft
  • 22 |
23 | 25 | 27 |

category, corresponding to one of the area of the developer site

28 | 29 | 30 |
31 | 32 | 33 |

This is the last step

34 | 35 | 36 |
37 | 38 |
39 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-simple.md/example-snap-tutorial/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "example-snap-tutorial", 3 | "duration": 6, 4 | "title": "Example snap tutorial", 5 | "summary": "This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words", 6 | "theme": "", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snapcraft" 12 | ], 13 | "tags": [ 14 | "content-interfaces", 15 | "interfaces", 16 | "up-to-four" 17 | ], 18 | "feedback": "http://Link", 19 | "difficulty": 2, 20 | "published": "2017-01-13T00:00:01Z", 21 | "url": "example-snap-tutorial" 22 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-simple.md/example-snap-tutorial/img/128451a661545188.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images-simple.md/example-snap-tutorial/img/128451a661545188.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images-simple.md/example-snap-tutorial/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 |

A, local image

11 |

12 | 13 | 14 |
15 | 16 | 17 |

At the top, you saw some medata, here are additional notes to them:

18 |
    19 |
  • Id would be used for url (tutorial/)
  • 20 |
  • Title is 5 years max
  • 21 |
  • Status: either Published or Draft
  • 22 |
23 | 25 | 27 |

category, corresponding to one of the area of the developer site

28 | 29 | 30 |
31 | 32 | 33 |

This is the last step

34 | 35 | 36 |
37 | 38 |
39 | -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images.md/example-snap-tutorial/codelab.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "example-snap-tutorial", 3 | "duration": 6, 4 | "title": "Example snap tutorial", 5 | "summary": "This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words", 6 | "theme": "", 7 | "status": [ 8 | "published" 9 | ], 10 | "category": [ 11 | "snapcraft" 12 | ], 13 | "tags": [ 14 | "content-interfaces", 15 | "interfaces", 16 | "up-to-four" 17 | ], 18 | "feedback": "http://Link", 19 | "difficulty": 2, 20 | "published": "2017-01-13T00:00:01Z", 21 | "url": "example-snap-tutorial" 22 | } -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images.md/example-snap-tutorial/img/128451a661545188.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images.md/example-snap-tutorial/img/128451a661545188.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images.md/example-snap-tutorial/img/38e08f189734d781.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images.md/example-snap-tutorial/img/38e08f189734d781.jpg -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images.md/example-snap-tutorial/img/38e08f189734d781.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images.md/example-snap-tutorial/img/38e08f189734d781.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images.md/example-snap-tutorial/img/9d4087c57696f1bc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabgenerated/markdown-with-images.md/example-snap-tutorial/img/9d4087c57696f1bc.png -------------------------------------------------------------------------------- /codelab/testdata/codelabgenerated/markdown-with-images.md/example-snap-tutorial/index.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | 9 | 10 |

A local image

11 |

12 |

A remote image in jpg

13 |

14 |

A remote image in jpg

15 |

16 |

A relative image, in upper directory

17 |

18 |

Extensions are kept

19 |

20 | 21 | 22 |
23 | 24 | 25 |

At the top, you saw some medata, here are additional notes to them:

26 |
    27 |
  • Id would be used for url (tutorial/)
  • 28 |
  • Title is 5 years max
  • 29 |
  • Status: either Published or Draft
  • 30 |
31 | 33 | 35 |

category, corresponding to one of the area of the developer site

36 | 37 | 38 |
39 | 40 | 41 |

This is the last step

42 | 43 | 44 |
45 | 46 |
47 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/bar.png: -------------------------------------------------------------------------------- 1 | foo.png -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/baz.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabsrc/baz.jpg -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/foo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/codelabsrc/foo.png -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-invalid-generated-html.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 2 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step 16 | Duration: 1:00 17 | 18 | First step simple content 19 | 20 | ## Metadata page 21 | Duration: 2:00 22 | 23 | At the top, you saw some medata, here are additional notes to them: 24 | * Id would be used for url (tutorial/) 25 | * Title is 5 years max 26 | * Status: either Published or Draft 27 | 28 | Positive 29 | : This will appear in a positive info box. 30 | 31 | Negative 32 | : This will appear in a negative info box. 33 | 34 | category, corresponding to one of the area of the developer site 35 | 36 | ## Last step 37 | Duration: 3:00 38 | 39 | This is the last step 40 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-missing-image.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 2 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step images 16 | Duration: 1:00 17 | 18 | A local image 19 | 20 | ![My alternative text for foo](foo.png) 21 | 22 | A remote image in jpg 23 | 24 | Missing image 25 | 26 | ![A missing image](unexisting.png) 27 | 28 | ## Metadata page 29 | Duration: 2:00 30 | 31 | At the top, you saw some medata, here are additional notes to them: 32 | * Id would be used for url (tutorial/) 33 | * Title is 5 years max 34 | * Status: either Published or Draft 35 | 36 | Positive 37 | : This will appear in a positive info box. 38 | 39 | Negative 40 | : This will appear in a negative info box. 41 | 42 | category, corresponding to one of the area of the developer site 43 | 44 | ## Last step 45 | Duration: 3:00 46 | 47 | This is the last step 48 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-modified-image.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 2 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step images 16 | Duration: 1:00 17 | 18 | A, local image 19 | 20 | ![My alternative text for foo](foo.png) 21 | 22 | ## Metadata page 23 | Duration: 2:00 24 | 25 | At the top, you saw some medata, here are additional notes to them: 26 | * Id would be used for url (tutorial/) 27 | * Title is 5 years max 28 | * Status: either Published or Draft 29 | 30 | Positive 31 | : This will appear in a positive info box. 32 | 33 | Negative 34 | : This will appear in a negative info box. 35 | 36 | category, corresponding to one of the area of the developer site 37 | 38 | ## Last step 39 | Duration: 3:00 40 | 41 | This is the last step 42 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-no-image.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 1 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step 16 | Duration: 1:00 17 | 18 | First step simple content 19 | 20 | ## Metadata page 21 | Duration: 2:00 22 | 23 | At the top, you saw some medata, here are additional notes to them: 24 | * Id would be used for url (tutorial/) 25 | * Title is 5 years max 26 | * Status: either Published or Draft 27 | 28 | Positive 29 | : This will appear in a positive info box. 30 | 31 | Negative 32 | : This will appear in a negative info box. 33 | 34 | category, corresponding to one of the area of the developer site 35 | 36 | ## Last step 37 | Duration: 3:00 38 | 39 | This is the last step 40 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-with-images-duplicate-images.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 2 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step images 16 | Duration: 1:00 17 | 18 | A, local image 19 | 20 | ![My alternative text for foo](foo.png) 21 | 22 | A relative image, in upper directory 23 | 24 | ![My alternative text for bar.png](bar.png) 25 | 26 | ## Metadata page 27 | Duration: 2:00 28 | 29 | At the top, you saw some medata, here are additional notes to them: 30 | * Id would be used for url (tutorial/) 31 | * Title is 5 years max 32 | * Status: either Published or Draft 33 | 34 | Positive 35 | : This will appear in a positive info box. 36 | 37 | Negative 38 | : This will appear in a negative info box. 39 | 40 | category, corresponding to one of the area of the developer site 41 | 42 | ## Last step 43 | Duration: 3:00 44 | 45 | This is the last step 46 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-with-images-extension-preserved.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 2 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step images 16 | Duration: 1:00 17 | 18 | A local image 19 | 20 | ![My alternative text for foo](foo.png) 21 | 22 | Extensions are kept 23 | 24 | ![My alternative text baz.jpg](baz.jpg) 25 | 26 | ## Metadata page 27 | Duration: 2:00 28 | 29 | At the top, you saw some medata, here are additional notes to them: 30 | * Id would be used for url (tutorial/) 31 | * Title is 5 years max 32 | * Status: either Published or Draft 33 | 34 | Positive 35 | : This will appear in a positive info box. 36 | 37 | Negative 38 | : This will appear in a negative info box. 39 | 40 | category, corresponding to one of the area of the developer site 41 | 42 | ## Last step 43 | Duration: 3:00 44 | 45 | This is the last step 46 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-with-images-online-jpg.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 2 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step images 16 | Duration: 1:00 17 | 18 | A remote image in jpg 19 | 20 | ![Remote jpg](https://design.ubuntu.com/wp-content/uploads/bcce/cof_orange_hex.jpg) 21 | 22 | ## Metadata page 23 | Duration: 2:00 24 | 25 | At the top, you saw some medata, here are additional notes to them: 26 | * Id would be used for url (tutorial/) 27 | * Title is 5 years max 28 | * Status: either Published or Draft 29 | 30 | Positive 31 | : This will appear in a positive info box. 32 | 33 | Negative 34 | : This will appear in a negative info box. 35 | 36 | category, corresponding to one of the area of the developer site 37 | 38 | ## Last step 39 | Duration: 3:00 40 | 41 | This is the last step 42 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-with-images-online.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 2 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step images 16 | Duration: 1:00 17 | 18 | A remote image 19 | 20 | ![Other image](https://wiki.videolan.org/images/Ubuntu-logo.png) 21 | 22 | ## Metadata page 23 | Duration: 2:00 24 | 25 | At the top, you saw some medata, here are additional notes to them: 26 | * Id would be used for url (tutorial/) 27 | * Title is 5 years max 28 | * Status: either Published or Draft 29 | 30 | Positive 31 | : This will appear in a positive info box. 32 | 33 | Negative 34 | : This will appear in a negative info box. 35 | 36 | category, corresponding to one of the area of the developer site 37 | 38 | ## Last step 39 | Duration: 3:00 40 | 41 | This is the last step 42 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-with-images-relative-upper-path.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 2 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step images 16 | Duration: 1:00 17 | 18 | A relative image, in upper directory 19 | 20 | ![My alternative text for ../bar.png](../bar.png) 21 | 22 | ## Metadata page 23 | Duration: 2:00 24 | 25 | At the top, you saw some medata, here are additional notes to them: 26 | * Id would be used for url (tutorial/) 27 | * Title is 5 years max 28 | * Status: either Published or Draft 29 | 30 | Positive 31 | : This will appear in a positive info box. 32 | 33 | Negative 34 | : This will appear in a negative info box. 35 | 36 | category, corresponding to one of the area of the developer site 37 | 38 | ## Last step 39 | Duration: 3:00 40 | 41 | This is the last step 42 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-with-images-simple.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 2 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step images 16 | Duration: 1:00 17 | 18 | A, local image 19 | 20 | ![My alternative text for foo](foo.png) 21 | 22 | ## Metadata page 23 | Duration: 2:00 24 | 25 | At the top, you saw some medata, here are additional notes to them: 26 | * Id would be used for url (tutorial/) 27 | * Title is 5 years max 28 | * Status: either Published or Draft 29 | 30 | Positive 31 | : This will appear in a positive info box. 32 | 33 | Negative 34 | : This will appear in a negative info box. 35 | 36 | category, corresponding to one of the area of the developer site 37 | 38 | ## Last step 39 | Duration: 3:00 40 | 41 | This is the last step 42 | -------------------------------------------------------------------------------- /codelab/testdata/codelabsrc/markdown-with-images.md: -------------------------------------------------------------------------------- 1 | --- 2 | id:example-snap-tutorial 3 | summary:This tutorial is going to cover a very very interesting topic, but the summary have to stay under 26 words 4 | categories: snapcraft 5 | tags: interfaces,content-interfaces,up-to-four 6 | difficulty: 2 7 | status: Published 8 | published: 2017-01-13 9 | feedback link: http://Link 10 | 11 | --- 12 | 13 | # Example snap tutorial 14 | 15 | ## First step images 16 | Duration: 1:00 17 | 18 | A local image 19 | 20 | ![My alternative text for foo](foo.png) 21 | 22 | A remote image in jpg 23 | 24 | ![Other image](https://wiki.videolan.org/images/Ubuntu-logo.png) 25 | 26 | A remote image in jpg 27 | 28 | ![Remote jpg](https://design.ubuntu.com/wp-content/uploads/bcce/cof_orange_hex.jpg) 29 | 30 | A relative image, in upper directory 31 | 32 | ![My alternative text for ../bar.png](../bar.png) 33 | 34 | Extensions are kept 35 | 36 | ![My alternative text baz.jpg](baz.jpg) 37 | 38 | ## Metadata page 39 | Duration: 2:00 40 | 41 | At the top, you saw some medata, here are additional notes to them: 42 | * Id would be used for url (tutorial/) 43 | * Title is 5 years max 44 | * Status: either Published or Draft 45 | 46 | Positive 47 | : This will appear in a positive info box. 48 | 49 | Negative 50 | : This will appear in a negative info box. 51 | 52 | category, corresponding to one of the area of the developer site 53 | 54 | ## Last step 55 | Duration: 3:00 56 | 57 | This is the last step 58 | -------------------------------------------------------------------------------- /codelab/testdata/flat/tut1.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/flat/tut1.md -------------------------------------------------------------------------------- /codelab/testdata/flat/tut2.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/flat/tut2.md -------------------------------------------------------------------------------- /codelab/testdata/flat2/tut1.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/flat2/tut1.md -------------------------------------------------------------------------------- /codelab/testdata/nested/subdir1/subsub/tut1.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/nested/subdir1/subsub/tut1.md -------------------------------------------------------------------------------- /codelab/testdata/nested/subdir1/subsub/tut2.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/nested/subdir1/subsub/tut2.md -------------------------------------------------------------------------------- /codelab/testdata/nested/subdir2/tut1.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/nested/subdir2/tut1.md -------------------------------------------------------------------------------- /codelab/testdata/nested/subdir2/tut2.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/nested/subdir2/tut2.md -------------------------------------------------------------------------------- /codelab/testdata/nothing/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/nothing/.keep -------------------------------------------------------------------------------- /codelab/testdata/template.html: -------------------------------------------------------------------------------- 1 | 5 | 8 | {{range .Steps}} 9 | 10 | {{.Content | renderHTML ""}} 11 | 12 | {{end}} 13 | 14 | -------------------------------------------------------------------------------- /codelab/testdata/withgdoc/gdoc.def: -------------------------------------------------------------------------------- 1 | # This is a comment that should be ignored 2 | 3 | mytut1 4 | mytut2 5 | 6 | # Another ignored comment 7 | -------------------------------------------------------------------------------- /codelab/testdata/withgdocduplicate/gdoc.def: -------------------------------------------------------------------------------- 1 | mytut1 2 | mytut2 3 | mytut1 4 | -------------------------------------------------------------------------------- /codelab/testdata/withignored/_part.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/withignored/_part.md -------------------------------------------------------------------------------- /codelab/testdata/withignored/img/foo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/withignored/img/foo.png -------------------------------------------------------------------------------- /codelab/testdata/withignored/something.blob: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/withignored/something.blob -------------------------------------------------------------------------------- /codelab/testdata/withignored/tut1.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/codelab/testdata/withignored/tut1.md -------------------------------------------------------------------------------- /consts/consts.go: -------------------------------------------------------------------------------- 1 | package consts 2 | 3 | const ( 4 | // GdocPrefix appending to detect google docs in refs 5 | GdocPrefix = "gdoc:" 6 | // TemplateFileName relative to metadata path 7 | TemplateFileName = "ubuntu-template.html" 8 | 9 | // APIURL is where API files are served on the webserver 10 | APIURL = "/api/" 11 | // ImagesURL is where images and other generated assets from API are served on the webserver 12 | ImagesURL = "/images/assets/" 13 | // CodelabSrcURL is where codelab source files are served on the webserver 14 | CodelabSrcURL = "/src/codelabs/" 15 | // ServeRootURL will always serve the / directory and server-side routing will do the redirect 16 | ServeRootURL = "/tutorial/" 17 | ) 18 | -------------------------------------------------------------------------------- /internaltools/unique.go: -------------------------------------------------------------------------------- 1 | package internaltools 2 | 3 | // UniqueStrings returns a unique subset of the string slice provided. 4 | func UniqueStrings(input []string) []string { 5 | u := make([]string, 0, len(input)) 6 | m := make(map[string]bool) 7 | 8 | for _, val := range input { 9 | if _, ok := m[val]; !ok { 10 | m[val] = true 11 | u = append(u, val) 12 | } 13 | } 14 | 15 | if len(u) == 0 { 16 | u = nil 17 | } 18 | 19 | return u 20 | } 21 | -------------------------------------------------------------------------------- /internaltools/unique_test.go: -------------------------------------------------------------------------------- 1 | package internaltools 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "testing" 7 | ) 8 | 9 | func TestUnique(t *testing.T) { 10 | testCases := []struct { 11 | elems []string 12 | want []string 13 | }{ 14 | {[]string{"/foo/bar", "/foo/baz", "ta"}, []string{"/foo/bar", "/foo/baz", "ta"}}, 15 | {[]string{"/foo/bar", "/foo/baz", "/foo/bar", "ta"}, []string{"/foo/bar", "/foo/baz", "ta"}}, 16 | {nil, nil}, 17 | } 18 | for _, tc := range testCases { 19 | t.Run(fmt.Sprintf("with %s", tc.elems), func(t *testing.T) { 20 | elems := UniqueStrings(tc.elems) 21 | if !reflect.DeepEqual(elems, tc.want) { 22 | t.Errorf("got %+v; want %+v", elems, tc.want) 23 | } 24 | }) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /paths/paths.go: -------------------------------------------------------------------------------- 1 | package paths 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | "path" 9 | "path/filepath" 10 | "sync" 11 | 12 | "github.com/ubuntu/tutorial-deployment/consts" 13 | ) 14 | 15 | const ( 16 | defaultRelativeExportPath = "src/codelabs" 17 | defaultRelativeMetadataPath = "metadata" 18 | defaultRelativeAPIPath = "api" 19 | defaultRelativeImagesPath = "images/assets" 20 | defaultTutorialPath = "tutorials" 21 | 22 | // GdocFilename for tutorials in google doc format. 23 | GdocFilename = "gdoc.def" 24 | ) 25 | 26 | func init() { 27 | p := New() 28 | flag.StringVar(&p.Website, "w", "", "website root path directory where main index.html is located. Will "+ 29 | "autodetect if current directory is within the website repository") 30 | flag.StringVar(&p.Export, "e", defaultRelativeExportPath, 31 | fmt.Sprintf("export path for generated tutorials. Default is [WEBSITE_PATH]/%s", defaultRelativeExportPath)) 32 | flag.StringVar(&p.MetaData, "m", defaultRelativeMetadataPath, 33 | fmt.Sprintf("import path for metadata as template and events definition. Default is [WEBSITE_PATH]/%s", defaultRelativeMetadataPath)) 34 | flag.StringVar(&p.API, "a", defaultRelativeAPIPath, 35 | fmt.Sprintf("exported apis for generated tutorials. Default is [WEBSITE_PATH]/%s", defaultRelativeAPIPath)) 36 | flag.StringVar(&p.Images, "i", defaultRelativeImagesPath, 37 | fmt.Sprintf("exported images asset directory for generated events and other things linked in the API file. Default is [WEBSITE_PATH]/%s", defaultRelativeImagesPath)) 38 | } 39 | 40 | var ( 41 | // paths encapsulate global path properties of the project 42 | paths Path 43 | onePath sync.Once 44 | ) 45 | 46 | // Path is used for the main Paths object 47 | type Path struct { 48 | Website string 49 | Export string 50 | MetaData string 51 | API string 52 | Images string 53 | TutorialInputs []string 54 | 55 | // are out paths export and api temporary? (prevent accidental deletion) 56 | tempRootPath string 57 | } 58 | 59 | // New get access to the singleton path and create it if necessary (multi-threading safe) 60 | func New() *Path { 61 | onePath.Do(func() { 62 | paths = Path{ 63 | Export: defaultRelativeExportPath, 64 | MetaData: defaultRelativeMetadataPath, 65 | API: defaultRelativeAPIPath, 66 | Images: defaultRelativeImagesPath, 67 | } 68 | }) 69 | return &paths 70 | } 71 | 72 | // ImportTutorialPaths sanitizes relative paths, adding default if none provided 73 | func (p *Path) ImportTutorialPaths(tps []string) (err error) { 74 | // default: tutorial and google doc reference path 75 | if len(tps) == 0 { 76 | tps = []string{path.Join(p.Website, defaultTutorialPath)} 77 | } 78 | for i, tp := range tps { 79 | if tp, err = filepath.Abs(tp); err != nil { 80 | if err != nil { 81 | return err 82 | } 83 | } 84 | tps[i] = tp 85 | } 86 | p.TutorialInputs = tps 87 | return nil 88 | } 89 | 90 | // CreateTempOutPath generate some temporary paths for API and export 91 | func (p *Path) CreateTempOutPath() error { 92 | tmp, err := ioutil.TempDir("", "serve-tutorial-") 93 | if err != nil { 94 | return fmt.Errorf("Couldn't create temp path: %s", err) 95 | } 96 | p.tempRootPath = tmp 97 | p.API = path.Join(tmp, consts.APIURL) 98 | p.Export = path.Join(tmp, consts.CodelabSrcURL) 99 | p.Images = path.Join(tmp, consts.ImagesURL) 100 | return nil 101 | } 102 | 103 | // CleanTempPath removes all generated paths 104 | func (p *Path) CleanTempPath() error { 105 | if p.tempRootPath == "" { 106 | return fmt.Errorf("No path in %+v corresponding to temporary paths", p) 107 | } 108 | p.API = "" 109 | p.Export = "" 110 | p.Images = "" 111 | return os.RemoveAll(p.tempRootPath) 112 | } 113 | 114 | // DetectPaths search for paths and load them accordingly to flags 115 | // this needs to be called after parsing the CLI args. 116 | func (p *Path) DetectPaths() (err error) { 117 | // We only need Website if one of the values aren't defined 118 | if p.Website == "" && 119 | (p.Export == defaultRelativeExportPath || p.MetaData == defaultRelativeMetadataPath || p.API == defaultRelativeAPIPath || p.Images == defaultRelativeImagesPath) { 120 | p.Website, err = detectWebsitePath() 121 | if err != nil { 122 | return err 123 | } 124 | } 125 | 126 | if err = sanitizeRelPathToWebsite(&p.Export, defaultRelativeExportPath, p.Website); err != nil { 127 | return err 128 | } 129 | if err = sanitizeRelPathToWebsite(&p.MetaData, defaultRelativeMetadataPath, p.Website); err != nil { 130 | return err 131 | } 132 | if err = sanitizeRelPathToWebsite(&p.API, defaultRelativeAPIPath, p.Website); err != nil { 133 | return err 134 | } 135 | if err = sanitizeRelPathToWebsite(&p.Images, defaultRelativeImagesPath, p.Website); err != nil { 136 | return err 137 | } 138 | return nil 139 | } 140 | 141 | func detectWebsitePath() (string, error) { 142 | rootDirFiles := [...]string{"index.html", "bower.json"} 143 | initdir := "." 144 | initdir, err := filepath.Abs(initdir) 145 | if err != nil { 146 | return "", err 147 | } 148 | dir := initdir 149 | 150 | RootDirsLoop: 151 | for dir != "/" { 152 | for _, file := range rootDirFiles { 153 | if _, err := os.Stat(path.Join(dir, file)); os.IsNotExist(err) { 154 | dir = path.Join(dir, "..") 155 | dir, err = filepath.Abs(dir) 156 | if err != nil { 157 | return "", err 158 | } 159 | continue RootDirsLoop 160 | } 161 | } 162 | break 163 | } 164 | // Root can't be website directory 165 | if dir == "/" { 166 | return "", fmt.Errorf("no website directory from and in parent directories of %s", initdir) 167 | } 168 | dir, err = filepath.Abs(dir) 169 | if err != nil { 170 | return "", err 171 | } 172 | 173 | return dir, nil 174 | } 175 | 176 | func sanitizeRelPathToWebsite(p *string, defP, website string) (err error) { 177 | if *p == defP { 178 | *p = path.Join(website, defP) 179 | } 180 | if *p, err = filepath.Abs(*p); err != nil { 181 | return err 182 | } 183 | return nil 184 | } 185 | 186 | // MockPath is for testing purposes only, enabling easy path mocking 187 | func MockPath() (*Path, func()) { 188 | origpath := paths 189 | 190 | return &paths, func() { 191 | paths = origpath 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /paths/paths_test.go: -------------------------------------------------------------------------------- 1 | package paths 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "reflect" 7 | "strings" 8 | "testing" 9 | 10 | "github.com/ubuntu/tutorial-deployment/testtools" 11 | ) 12 | 13 | func TestDetectPaths(t *testing.T) { 14 | testCases := []struct { 15 | websitePath string 16 | exportPath string 17 | metadataPath string 18 | apiPath string 19 | imagePath string 20 | cwd string 21 | 22 | // the wanted paths are relative to cwd defined above 23 | wantWebsitePath string 24 | wantExportPath string 25 | wantMetaDataPath string 26 | wantAPIPath string 27 | wantImagesPath string 28 | wantErr bool 29 | }{ 30 | {"/defined/website", "/other/export", "/metadata", "/api", "/images/assets", "", "/defined/website", "/other/export", "/metadata", "/api", "/images/assets", false}, 31 | {"/defined/website", "export/path", "alt/metadata", "alt/api", "alt/images/assets", "", "/defined/website", "export/path", "alt/metadata", "alt/api", "alt/images/assets", false}, 32 | {"", "export/path", "alt/metadata", "alt/api", "alt/images/assets", "", "", "export/path", "alt/metadata", "alt/api", "alt/images/assets", false}, // The 3 parameters are sufficient to avoid needing website root detection 33 | {"", paths.Export, "alt/metadata", "alt/api", "alt/images/assets", "testdata/nosite", "", "", "", "", "alt/images/assets", true}, // Error due to no site detected 34 | {"", paths.Export, "alt/metadata", "alt/api", "alt/images/assets", "testdata/partialwebsite", "", "", "", "", "alt/images/assets", true}, // Error due to no site detected 35 | {"", paths.Export, "alt/metadata", "alt/api", "alt/images/assets", "testdata/website", ".", defaultRelativeExportPath, "alt/metadata", "alt/api", "alt/images/assets", false}, // Defined path are always relative to cwd, not website 36 | {"", paths.Export, "alt/metadata", "alt/api", "alt/images/assets", "testdata/website/subdir", "..", "../" + defaultRelativeExportPath, "alt/metadata", "alt/api", "alt/images/assets", false}, // Subdir path detection 37 | {"", paths.Export, paths.MetaData, paths.API, paths.Images, "testdata/website", ".", defaultRelativeExportPath, defaultRelativeMetadataPath, defaultRelativeAPIPath, defaultRelativeImagesPath, false}, 38 | } 39 | for _, tc := range testCases { 40 | t.Run(fmt.Sprintf("(website: %s), (export: %s), (metadata: %s), (api: %s), , (images: %s) in [%s]", 41 | tc.websitePath, tc.exportPath, tc.metadataPath, tc.apiPath, tc.imagePath, tc.cwd), func(t *testing.T) { 42 | // Setup/Teardown 43 | defer testtools.Chdir(t, tc.cwd)() 44 | cachepath, teardown := MockPath() 45 | defer teardown() 46 | cachepath.Website = tc.websitePath 47 | cachepath.Export = tc.exportPath 48 | cachepath.MetaData = tc.metadataPath 49 | cachepath.API = tc.apiPath 50 | cachepath.Images = tc.imagePath 51 | if tc.wantWebsitePath != "" { 52 | tc.wantWebsitePath = testtools.AbsPath(t, tc.wantWebsitePath) 53 | } 54 | tc.wantExportPath = testtools.AbsPath(t, tc.wantExportPath) 55 | tc.wantMetaDataPath = testtools.AbsPath(t, tc.wantMetaDataPath) 56 | tc.wantAPIPath = testtools.AbsPath(t, tc.wantAPIPath) 57 | tc.wantImagesPath = testtools.AbsPath(t, tc.wantImagesPath) 58 | 59 | // Test 60 | p := New() 61 | err := p.DetectPaths() 62 | 63 | // Error checking 64 | if err != nil != tc.wantErr { 65 | t.Errorf("DetectPaths() error = %v, wantErr %v", err, tc.wantErr) 66 | return 67 | } 68 | if err != nil { 69 | // Error is fatal, we don't care about paths 70 | return 71 | } 72 | 73 | // Paths checks 74 | if p.Website != tc.wantWebsitePath { 75 | t.Errorf("Website: got %s; want %s", p.Website, tc.wantWebsitePath) 76 | } 77 | if p.Export != tc.wantExportPath { 78 | t.Errorf("Export: got %s; want %s", p.Export, tc.wantExportPath) 79 | } 80 | if p.MetaData != tc.wantMetaDataPath { 81 | t.Errorf("Metadata: got %s; want %s", p.MetaData, tc.wantMetaDataPath) 82 | } 83 | if p.API != tc.wantAPIPath { 84 | t.Errorf("API: got %s; want %s", p.API, tc.wantAPIPath) 85 | } 86 | if p.Images != tc.wantImagesPath { 87 | t.Errorf("Images: got %s; want %s", p.Images, tc.wantImagesPath) 88 | } 89 | }) 90 | } 91 | } 92 | 93 | func TestImportTutorialPaths(t *testing.T) { 94 | website := "/ws/" 95 | testCases := []struct { 96 | paths []string 97 | wantPaths []string 98 | }{ 99 | {nil, []string{website + defaultTutorialPath}}, 100 | {[]string{"/rep1", "/rep2/tut1.md", "/rep3/rep5"}, []string{"/rep1", "/rep2/tut1.md", "/rep3/rep5"}}, 101 | {[]string{"rep1", "../rep2/tut1.md", "rep3/rep5"}, []string{"rep1", "../rep2/tut1.md", "rep3/rep5"}}, 102 | {[]string{"/foo/rep1"}, []string{"/foo/rep1"}}, 103 | } 104 | for _, tc := range testCases { 105 | t.Run(fmt.Sprintf("path argument: %+v", tc.paths), func(t *testing.T) { 106 | // Setup/Teardown 107 | p := Path{ 108 | Website: website, 109 | } 110 | for i, want := range tc.wantPaths { 111 | tc.wantPaths[i] = testtools.AbsPath(t, want) 112 | } 113 | 114 | // Test 115 | err := p.ImportTutorialPaths(tc.paths) 116 | if err != nil { 117 | t.Errorf("err: %s", err) 118 | } 119 | 120 | if !reflect.DeepEqual(p.TutorialInputs, tc.wantPaths) { 121 | t.Errorf("Import path: got %+v; want %+v", p.TutorialInputs, tc.wantPaths) 122 | } 123 | }) 124 | } 125 | } 126 | 127 | func TestCreateTempPathHandling(t *testing.T) { 128 | p := Path{} 129 | 130 | // Create temp dir 131 | if err := p.CreateTempOutPath(); err != nil { 132 | t.Fatalf("err: %s", err) 133 | } 134 | 135 | if p.API == "" || p.Export == "" || p.Images == "" { 136 | t.Errorf("one of API (%s) or Export (%s) or Images (%s) is empty", p.API, p.Export, p.Images) 137 | return 138 | } 139 | tmpdir := p.API[:len(p.API)-len(defaultRelativeAPIPath)] 140 | if !strings.HasPrefix(p.Export, tmpdir) { 141 | t.Errorf("API (%s) and Export (%s) don't have the same temporary prefix", p.API, p.Export) 142 | } 143 | if !strings.HasPrefix(p.Images, tmpdir) { 144 | t.Errorf("API (%s) and Images (%s) don't have the same temporary prefix", p.API, p.Images) 145 | } 146 | if _, err := os.Stat(tmpdir); os.IsNotExist(err) { 147 | t.Errorf("%s doesn't exists", tmpdir) 148 | return 149 | } 150 | 151 | // Remove temp dir 152 | if err := p.CleanTempPath(); err != nil { 153 | t.Fatalf("err: %s", err) 154 | } 155 | 156 | if _, err := os.Stat(tmpdir); err == nil { 157 | t.Errorf("%s still exists", tmpdir) 158 | } 159 | if p.API != "" || p.Export != "" || p.Images != "" { 160 | t.Errorf("API (%s), Export (%s) and Images (%s) should now be empty", p.API, p.Export, p.Images) 161 | } 162 | } 163 | 164 | func TestTryCleanNonTempDir(t *testing.T) { 165 | p := Path{} 166 | 167 | if err := p.CleanTempPath(); err == nil { 168 | t.Errorf("Cleaning a non temporary path object should have returned an error: %+v", p) 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /paths/testdata/nosite/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/paths/testdata/nosite/.keep -------------------------------------------------------------------------------- /paths/testdata/partialwebsite/index.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/paths/testdata/partialwebsite/index.html -------------------------------------------------------------------------------- /paths/testdata/website/bower.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/paths/testdata/website/bower.json -------------------------------------------------------------------------------- /paths/testdata/website/index.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/paths/testdata/website/index.html -------------------------------------------------------------------------------- /paths/testdata/website/subdir/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ubuntu/tutorial-deployment/c7c7247899da46b9757d1ccf925fd96934b75358/paths/testdata/website/subdir/.keep -------------------------------------------------------------------------------- /runtests: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | 3 | go test -v ./... | tee tests.log 4 | returncode="${PIPESTATUS[0]}" 5 | 6 | NUMTESTS=`grep RUN tests.log | wc -l` 7 | echo "RAN $NUMTESTS tests" 8 | 9 | [ $returncode -ne 0 ] && echo "Some tests FAILED" 10 | exit $returncode 11 | -------------------------------------------------------------------------------- /testtools/tools.go: -------------------------------------------------------------------------------- 1 | package testtools 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "path/filepath" 7 | "testing" 8 | ) 9 | 10 | // TempDir is a setup/teardown test helper for creating a temporary directory 11 | func TempDir(t *testing.T) (string, func()) { 12 | path, err := ioutil.TempDir("", "tutorial-test") 13 | if err != nil { 14 | t.Fatalf("err: %s", err) 15 | } 16 | return path, func() { 17 | if err := os.RemoveAll(path); err != nil { 18 | t.Fatalf("err: %s", err) 19 | } 20 | } 21 | } 22 | 23 | // StringContains check an element is contained in a slice of string 24 | func StringContains(s []string, e string) bool { 25 | for _, a := range s { 26 | if a == e { 27 | return true 28 | } 29 | } 30 | return false 31 | } 32 | 33 | // AbsPath is a simple abspath for absolute path test with test failure 34 | func AbsPath(t *testing.T, path string) string { 35 | path, err := filepath.Abs(path) 36 | if err != nil { 37 | t.Fatalf("err: %s", err) 38 | } 39 | return path 40 | } 41 | 42 | // Chdir is a setup/teadown test helper for changing current directory 43 | func Chdir(t *testing.T, dir string) func() { 44 | if dir == "" { 45 | return func() {} 46 | } 47 | old, err := os.Getwd() 48 | if err != nil { 49 | t.Fatalf("err: %s", err) 50 | } 51 | if err := os.Chdir(dir); err != nil { 52 | t.Fatalf("err: %s", err) 53 | } 54 | return func() { 55 | if err := os.Chdir(old); err != nil { 56 | t.Fatalf("err: %s", err) 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /websocket/websocket_test.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/http/httptest" 7 | "strings" 8 | "sync" 9 | "testing" 10 | "time" 11 | 12 | "github.com/gorilla/websocket" 13 | ) 14 | 15 | func TestHubStartStopNoClient(t *testing.T) { 16 | h, stopHub := createHub() 17 | if len(h.clients) != 0 { 18 | t.Errorf("No client should be registered. Got: %+v", h.clients) 19 | } 20 | stopHub() 21 | if len(h.clients) != 0 { 22 | t.Errorf("No client should be registered. Got: %+v", h.clients) 23 | } 24 | } 25 | 26 | func TestHubRegisterDeregisterClients(t *testing.T) { 27 | for _, numClient := range []int{0, 1, 2} { 28 | t.Run(fmt.Sprintf("register and deregister %d clients", numClient), func(t *testing.T) { 29 | h, stopHub := createHub() 30 | ts := httptest.NewServer(http.HandlerFunc(h.NewClient)) 31 | defer ts.Close() 32 | 33 | // connect our client(s) 34 | for i := 0; i < numClient; i++ { 35 | _, cleanup := addClient(t, ts.URL, h) 36 | defer cleanup() 37 | } 38 | 39 | h.muC.RLock() 40 | if len(h.clients) != numClient { 41 | t.Errorf("We expected %d clients to get registered. Got: %+v", numClient, h.clients) 42 | } 43 | h.muC.RUnlock() 44 | stopHub() 45 | if len(h.clients) != 0 { 46 | t.Errorf("We expected all clients to get deregistered. Got: %+v", h.clients) 47 | } 48 | }) 49 | } 50 | } 51 | 52 | func TestHubSendOneMessageToClients(t *testing.T) { 53 | for _, numClient := range []int{0, 1, 2} { 54 | t.Run(fmt.Sprintf("send message to %d clients", numClient), func(t *testing.T) { 55 | h, cleanup := createHub() 56 | defer cleanup() 57 | ts := httptest.NewServer(http.HandlerFunc(h.NewClient)) 58 | defer ts.Close() 59 | 60 | // connect our client(s) 61 | var clients []*websocket.Conn 62 | for i := 0; i < numClient; i++ { 63 | c, cleanup := addClient(t, ts.URL, h) 64 | clients = append(clients, c) 65 | defer cleanup() 66 | } 67 | 68 | msg := []byte("test") 69 | h.Send(msg) 70 | 71 | // ensure all clients received the desired message 72 | for _, c := range clients { 73 | _, rcv, err := c.ReadMessage() 74 | if err != nil { 75 | t.Fatalf("Unexpected received message error: %v", err) 76 | return 77 | } 78 | if string(rcv) != string(msg) { 79 | t.Errorf("We did send %s, but received %s", msg, rcv) 80 | } 81 | } 82 | 83 | }) 84 | } 85 | } 86 | 87 | func TestHubSendMultipleMessagesToClients(t *testing.T) { 88 | for _, numClient := range []int{0, 1, 2} { 89 | t.Run(fmt.Sprintf("send multiple messages to %d clients", numClient), func(t *testing.T) { 90 | h, cleanup := createHub() 91 | defer cleanup() 92 | ts := httptest.NewServer(http.HandlerFunc(h.NewClient)) 93 | defer ts.Close() 94 | 95 | // connect our client(s) 96 | var clients []*websocket.Conn 97 | for i := 0; i < numClient; i++ { 98 | c, cleanup := addClient(t, ts.URL, h) 99 | clients = append(clients, c) 100 | defer cleanup() 101 | } 102 | 103 | msgs := []string{"test", "test2"} 104 | for _, msg := range msgs { 105 | h.Send([]byte(msg)) 106 | } 107 | 108 | // ensure all clients received all the desired messages in correct order 109 | for _, c := range clients { 110 | for _, msg := range msgs { 111 | _, rcv, err := c.ReadMessage() 112 | if err != nil { 113 | t.Fatalf("Unexpected received message error: %v", err) 114 | return 115 | } 116 | 117 | if string(rcv) != string(msg) { 118 | t.Errorf("We did send %s, but received %s", msg, rcv) 119 | } 120 | } 121 | } 122 | }) 123 | } 124 | } 125 | 126 | func TestHubSendDefficientClients(t *testing.T) { 127 | h, cleanup := createHub() 128 | defer cleanup() 129 | ts := httptest.NewServer(http.HandlerFunc(h.NewClient)) 130 | defer ts.Close() 131 | 132 | // connect our client 133 | _, cleanup = addClient(t, ts.URL, h) 134 | defer cleanup() 135 | h.muC.RLock() 136 | var cl *client 137 | for c := range h.clients { 138 | cl = c 139 | } 140 | h.muC.RUnlock() 141 | 142 | h.unregister <- cl 143 | // wait for unregistration to proceed 144 | <-time.After(time.Millisecond) 145 | 146 | h.muC.RLock() 147 | if len(h.clients) != 0 { 148 | t.Errorf("We expected all clients to get deregistered. Got: %+v", h.clients) 149 | } 150 | h.muC.RUnlock() 151 | 152 | // that shouldn't block 153 | msg := []byte("test") 154 | h.Send(msg) 155 | } 156 | 157 | func TestClientClosingConnection(t *testing.T) { 158 | h, cleanup := createHub() 159 | defer cleanup() 160 | ts := httptest.NewServer(http.HandlerFunc(h.NewClient)) 161 | defer ts.Close() 162 | 163 | // connect our client 164 | _, closeClient := addClient(t, ts.URL, h) 165 | 166 | closeClient() 167 | 168 | // wait for unregistration to proceed 169 | <-time.After(time.Millisecond) 170 | h.muC.RLock() 171 | if len(h.clients) != 0 { 172 | t.Errorf("We expected all clients to get deregistered. Got: %+v", h.clients) 173 | } 174 | h.muC.RUnlock() 175 | } 176 | 177 | func TestClientAbnormalCloseConnection(t *testing.T) { 178 | h, cleanup := createHub() 179 | defer cleanup() 180 | ts := httptest.NewServer(http.HandlerFunc(h.NewClient)) 181 | defer ts.Close() 182 | 183 | // connect our client 184 | cl, _ := addClient(t, ts.URL, h) 185 | 186 | // close without message (will trigger a log message) 187 | cl.Close() 188 | 189 | // wait for unregistration to proceed 190 | <-time.After(time.Millisecond) 191 | h.muC.RLock() 192 | if len(h.clients) != 0 { 193 | t.Errorf("We expected all clients to get deregistered. Got: %+v", h.clients) 194 | } 195 | h.muC.RUnlock() 196 | } 197 | 198 | // createHub and return a teardown cleanup function 199 | func createHub() (*Hub, func()) { 200 | h := NewHub() 201 | wg := sync.WaitGroup{} 202 | wg.Add(1) 203 | go func() { 204 | defer wg.Done() 205 | h.Run() 206 | }() 207 | return h, func() { 208 | h.Stop() 209 | wg.Wait() 210 | } 211 | } 212 | 213 | func addClient(t *testing.T, httpURL string, hub *Hub) (*websocket.Conn, func()) { 214 | c, _, err := websocket.DefaultDialer.Dial(strings.Replace(httpURL, "http", "ws", 1), nil) 215 | if err != nil { 216 | t.Fatalf("Coudn't create websocket dialer: %v", err) 217 | } 218 | 219 | // wait for registration 220 | <-time.After(time.Millisecond) 221 | return c, func() { 222 | c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) 223 | c.Close() 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /websocket/wsClient.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | import ( 4 | "log" 5 | "net" 6 | "net/http" 7 | "time" 8 | 9 | "github.com/gorilla/websocket" 10 | ) 11 | 12 | const ( 13 | // Time allowed to write a message to the peer. 14 | writeWait = 10 * time.Second 15 | 16 | // Time allowed to read the next pong message from the peer. 17 | pongWait = 60 * time.Second 18 | 19 | // Send pings to peer with this period. Must be less than pongWait. 20 | pingPeriod = (pongWait * 9) / 10 21 | ) 22 | 23 | var upgrader = websocket.Upgrader{} 24 | 25 | // client is an middleman between the websocket connection and the hub. 26 | type client struct { 27 | hub *Hub 28 | 29 | // The websocket connection. 30 | conn *websocket.Conn 31 | 32 | // Buffered channel of outbound messages. 33 | send chan []byte 34 | } 35 | 36 | // reader get messages from the websocket connection to the hub. 37 | func (c *client) reader() { 38 | defer func() { 39 | c.hub.unregister <- c 40 | c.conn.Close() 41 | }() 42 | c.conn.SetReadLimit(512) 43 | c.conn.SetReadDeadline(time.Now().Add(pongWait)) 44 | c.conn.SetPongHandler(func(string) error { 45 | c.conn.SetReadDeadline(time.Now().Add(pongWait)) 46 | return nil 47 | }) 48 | for { 49 | _, _, err := c.conn.ReadMessage() 50 | if err != nil { 51 | switch err.(type) { 52 | case *net.OpError: 53 | case *websocket.CloseError: 54 | if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure) { 55 | log.Printf("An error happened when reading from the Websocket client: %v", err) 56 | } 57 | } 58 | break 59 | } 60 | } 61 | } 62 | 63 | // writer sends messages from the hub to the websocket connection. 64 | func (c *client) writer() { 65 | pingTicker := time.NewTicker(pingPeriod) 66 | defer func() { 67 | pingTicker.Stop() 68 | c.conn.Close() 69 | }() 70 | for { 71 | select { 72 | case message, ok := <-c.send: 73 | if !ok { 74 | // The hub closed the channel. 75 | c.conn.WriteMessage(websocket.CloseMessage, []byte{}) 76 | return 77 | } 78 | 79 | c.conn.SetWriteDeadline(time.Now().Add(writeWait)) 80 | if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil { 81 | return 82 | } 83 | 84 | case <-pingTicker.C: 85 | c.conn.SetWriteDeadline(time.Now().Add(writeWait)) 86 | if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil { 87 | return 88 | } 89 | } 90 | } 91 | } 92 | 93 | // NewClient create a new client connected to our hub and listen/write to a websocket. 94 | func (hub *Hub) NewClient(w http.ResponseWriter, r *http.Request) { 95 | conn, err := upgrader.Upgrade(w, r, nil) 96 | if err != nil { 97 | if _, ok := err.(websocket.HandshakeError); !ok { 98 | log.Println(err) 99 | } 100 | return 101 | } 102 | client := &client{hub: hub, conn: conn, send: make(chan []byte, 10)} 103 | client.hub.register <- client 104 | go client.writer() 105 | client.reader() 106 | } 107 | -------------------------------------------------------------------------------- /websocket/wsHub.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | import ( 4 | "sync" 5 | ) 6 | 7 | // Hub maintains the set of active clients and broadcasts messages to the clients. 8 | type Hub struct { 9 | broadcast chan []byte 10 | 11 | // the mutex is only for the tests 12 | muC *sync.RWMutex 13 | clients map[*client]bool 14 | 15 | register chan *client 16 | unregister chan *client 17 | stop chan struct{} 18 | } 19 | 20 | // NewHub generate the main Hub object to connect clients to it 21 | func NewHub() *Hub { 22 | return &Hub{ 23 | broadcast: make(chan []byte), 24 | muC: &sync.RWMutex{}, 25 | clients: make(map[*client]bool), 26 | register: make(chan *client), 27 | unregister: make(chan *client), 28 | stop: make(chan struct{}), 29 | } 30 | } 31 | 32 | // Run this our Hub for registering clients 33 | func (h *Hub) Run() { 34 | for { 35 | select { 36 | case client := <-h.register: 37 | h.muC.Lock() 38 | h.clients[client] = true 39 | h.muC.Unlock() 40 | case client := <-h.unregister: 41 | h.muC.Lock() 42 | if _, ok := h.clients[client]; ok { 43 | delete(h.clients, client) 44 | close(client.send) 45 | } 46 | h.muC.Unlock() 47 | case message := <-h.broadcast: 48 | for client := range h.clients { 49 | select { 50 | case client.send <- message: 51 | default: 52 | go func() { 53 | // handle that in a goroutine as the receiver is in the same goroutine 54 | h.unregister <- client 55 | }() 56 | } 57 | } 58 | case <-h.stop: 59 | for c := range h.clients { 60 | c.conn.Close() 61 | h.muC.Lock() 62 | delete(h.clients, c) 63 | h.muC.Unlock() 64 | } 65 | return 66 | } 67 | } 68 | } 69 | 70 | // Stop hub and disconnect all clients 71 | func (h *Hub) Stop() { 72 | close(h.stop) 73 | } 74 | 75 | // Send a message to all connected clients 76 | func (h *Hub) Send(msg []byte) { 77 | h.broadcast <- msg 78 | } 79 | --------------------------------------------------------------------------------