<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Living The Dream on Medium]]></title>
        <description><![CDATA[Stories by Living The Dream on Medium]]></description>
        <link>https://medium.com/@live-the-dreams?source=rss-832969f3b93------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_it6Gxcob0BqpCLP2PSKLw.png</url>
            <title>Stories by Living The Dream on Medium</title>
            <link>https://medium.com/@live-the-dreams?source=rss-832969f3b93------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:02:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@live-the-dreams/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Getting Webpack 5/Laravel-Mix public path dynamically set to your Shopify assets folder (Vue.js)]]></title>
            <link>https://live-the-dreams.medium.com/getting-webpack-5-laravel-mix-public-path-dynamically-set-to-your-shopify-assets-folder-vue-js-20932238c1b6?source=rss-832969f3b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/20932238c1b6</guid>
            <category><![CDATA[laravel-mix]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[shopify]]></category>
            <dc:creator><![CDATA[Living The Dream]]></dc:creator>
            <pubDate>Sat, 20 Mar 2021 13:22:42 GMT</pubDate>
            <atom:updated>2021-03-20T13:22:42.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpdCB8ssHVk6dpHL31rKbA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@yancymin?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Yancy Min</a> on Unsplash</figcaption></figure><h3>Getting Webpack 5/Laravel-Mix public path dynamically set to your Shopify assets folder (Vue.js/Others)</h3><blockquote>If you are using Webpack 5.x with ES6 imports to dynamically load modules for Vue.js/React.js components or similar optionally with Laravel-Mix then you may need to dynamically set the Webpack import path to the Shopify CDN asset_url folder, so that Webpack can find your dynamic module .js chunked files.</blockquote><h3>The problem</h3><p>When you use Webpack to generate chunked files or multiple bundle files using a standard setup Webpack would usually output your chunked files to assets/app/&lt;filename&gt;.js. When working with Shopify this will not be allowed to be uploaded to their CDN using Theme Kit. It will fail with a subfolders not allowed error. You must generate the chunks in the same directory as app.js, the root assets folder. You can do it in Mix using the following in the webpack.mix.js:</p><pre>mix.webpackConfig({<br>  output: {<br>    chunkFilename: &#39;assets/[name].chunk.[chunkhash:5].js&#39;<br>  }<br>});</pre><p>This will then allow you to do the following command to upload all of the chunks and your entry point &amp; library files as well:</p><pre>theme deploy assets/app.js assets/manifest.js assets/vendor.js assets/*chunk*.js -e=&lt;store theme&gt;</pre><p>Once they are on the Shopify CDN, Webpack needs to know the exact URL and complete path to that folder, without that Webpack will look for the chunked files in the default root path of the Shopify store, not the full asset_url path that Shopify needs us to use.</p><h3>The Solution</h3><p>Using a Liquid snippet we can get the value and pass it to Webpack at the right point.</p><p>Create a snippet in your theme’s snippets folder called webpack-public-path.liquid and paste in the following, this will allow us to set a global JavaScript variable on the window object with the value being the correct path:</p><pre>{% capture asset_path %}{{ &#39;app.js&#39; | asset_url }}{% endcapture %}<br>{% assign webpack_path = asset_path | split: &#39;app.js&#39; | first | replace: &#39;assets/&#39;, &#39;&#39; %}</pre><pre>&lt;script type=&quot;text/javascript&quot;&gt;<br><strong>// This will set the path into the global JavaScript scope so it can be picked up further down the path of execution.</strong>        window.__webpack_public_path__ = &#39;{{ webpack_path }}&#39;;<br>&lt;/script&gt;</pre><p>This will use your existing app.js asset url and then strip away the path so that Webpack can add assets/chunk-name.js to the end of the URL to include your async components or other dynamically loaded data:</p><pre>//cdn.shopify.com/s/files/1/xxxx/xxxx/xxxx/x/xx/</pre><p>Once Webpack modifies the URL to load in any further imports, it would become:</p><pre>//cdn.shopify.com/s/files/1/xxxx/xxxx/xxxx/x/xx/assets/chunk.js </pre><p>Next you need to tell Webpack that it needs to look in the correct place for the value before importing its dependancies. If you are using the same Laravel-Mix setup as I am, then it would need to be defined in the top of app.js.</p><h4>Updating The Entry Point</h4><p>You need to ensure it is at the top of all the lines in the file, due to the way this is carried out Webpack recommends you create a file called public-path.js in the same folder as your app.js and then include it as follows:</p><pre><strong>import &quot;./public-path&quot;;</strong><br>import Vue from &#39;Vue&#39;;<br>import _ from &#39;lodash-es&#39;;<br></pre><pre><strong>// Using an anonymous function you can split the components out into // the chunked files, only loading the components in use on the page // being rendered, increasing performance both on the browser and <br>// the network.</strong></pre><pre>Vue.component(&#39;test&#39;, () =&gt; import(&#39;./test.vue&#39;));</pre><h4>Setting The Public Path Variable</h4><p>The contents of the public-path.js file just needs to be this one line which grabs the value we set earlier in the page’s execution:</p><pre>__webpack_public_path__ = window.__webpack_public_path__;</pre><p>Once you have completed this, you need to add a render tag to theme.liquid to load up your Liquid snippet at the right time, above the entry point of your Webpack bundles.</p><pre>&lt;head&gt;</pre><pre>{% render &#39;meta&#39; %}</pre><pre><strong>{% render &#39;webpack-public-path&#39; %}</strong></pre><pre>{{ content_for_header }} </pre><pre>&lt;/head&gt;</pre><pre>&lt;body&gt;</pre><pre>&lt;script src=&quot;{{ &#39;manifest.js&#39; | asset_url }}&quot; defer&gt;&lt;/script&gt;<br>&lt;script src=&quot;{{ &#39;vendor.js&#39; | asset_url }}&quot; defer&gt;&lt;/script&gt;<br>&lt;script src=&quot;{{ &#39;app.js&#39; | asset_url }}&quot; defer&gt;&lt;/script&gt;</pre><pre>&lt;/body&gt;</pre><p>Now Webpack should be able to find all of your async loading chunks in the correct asset path folder. You can check the value yourself if required by adding this line temporarily to the top of the public-path.js file below the assignment of the variable. It should then show up in your browser console when visiting your store.</p><pre>__webpack_public_path__ = window.__webpack_public_path__;</pre><pre><strong>// Make sure to remove this line afterwards.</strong><br><strong>console.log(__webpack_public_path__);</strong></pre><h4>Finishing Up (Dynamic Imports)</h4><p>Next, if you have not yet changed all of your library, dependancy &amp; internal imports to use async loading, then you may need to setup the correct Babel plugins as well, you can do this by installing these packages:</p><pre>npm i --save @babel/preset-env@latest @babel/plugin-syntax-dynamic-import@latest</pre><p>Then create or edit your .babelrc configuration file to define the plugins in the settings used.</p><pre>{<br>  &quot;presets&quot;: [&quot;<a href="http://twitter.com/babel/preset-env">@babel/preset-env</a>&quot;],<br>  &quot;plugins&quot;: [&quot;<a href="http://twitter.com/babel/plugin-syntax-dynamic-imp">@babel/plugin-syntax-dynamic-imp</a>ort&quot;]<br>}</pre><p>Laravel-Mix &amp; Webpack should now use these Babel plugins to poly-fill the feature so that it works on all modern browsers, as its a bleeding edge feature of JavaScript at the moment. You should see an increase in performance and a dramatic reduction of the entry point file in favour of the many split-chunk files that you can now use on your theme.</p><p>Some libraries you use like jQuery, Lodash and others will possibly have different syntax for ES6 style importing or they will have separate packages for their ES6 versions, like lodash-es on npm.</p><p>So your require statements for these modules can now be changed to import statements, install the lodash-es package from npm and then change:</p><pre>var _ = require(&#39;lodash&#39;);</pre><p>To:</p><pre>import _ from &#39;lodash-es&#39;;</pre><h4>A Note On Uploading (Shopify Theme Kit)</h4><p>When using Shopify Theme Kit to deploy your theme files and assets, you need to now remember instead of being able to just execute:</p><pre>theme deploy assets/app.js assets/manifest.js assets/vendor.js -e=&lt;store theme&gt;</pre><p>You now have to make sure that all chunks get uploaded everytime you run npm run prod, using the following wildcard will help you upload all your Webpack files once done, without potentially doing *.js and catching non-Webpack JavaScript assets:</p><pre>theme deploy assets/app.js assets/*chunk*.js assets/manifest.js assets/vendor.js -e=&lt;store theme&gt;</pre><p><strong>Versions of software used:</strong></p><ul><li><em>Webpack: </em><strong><em>5.x</em></strong></li><li><em>Laravel-Mix: </em><strong><em>6.x</em></strong></li><li><em>Babel: </em><strong><em>7.x</em></strong></li><li><em>Shopify Theme Kit: </em><strong><em>1.1.x</em></strong></li></ul><p><strong>References / Docs:</strong></p><ul><li><a href="https://webpack.js.org/guides/public-path/">https://webpack.js.org/guides/public-path/</a></li><li><a href="https://shopify.dev/docs/themes/liquid/reference/filters/url-filters">https://shopify.dev/docs/themes/liquid/reference/filters/url-filters</a></li><li><a href="https://vuejs.org/v2/guide/components-dynamic-async.html">https://vuejs.org/v2/guide/components-dynamic-async.html</a></li><li><a href="https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import">https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20932238c1b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shopify Themekit — Feeding it deployments to avoid Protocol & HTTP errors]]></title>
            <link>https://live-the-dreams.medium.com/shopify-themekit-feeding-it-deployments-to-avoid-protocol-http-errors-feaa2c5d114d?source=rss-832969f3b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/feaa2c5d114d</guid>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[theme-kit]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[themes]]></category>
            <dc:creator><![CDATA[Living The Dream]]></dc:creator>
            <pubDate>Sun, 19 Apr 2020 16:01:31 GMT</pubDate>
            <atom:updated>2020-04-19T16:01:31.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFZAOkFfAFSom3buRPXx1g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Charles Deluvio</a> on <a href="https://unsplash.com/s/photos/shopify?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Shopify Theme Kit — Feeding it deployments to avoid Protocol &amp; HTTP errors</h3><p><strong>Note: You will need at least basic command line/Shopify/Shopify Theme Kit experience to easily understand this quick article.</strong></p><p>This is just a quick article based on an experience I had the other day. I should say that I have been using the Shopify platform for a full 10 years now and that this is no vendetta as my whole career is pretty much down to Shopify stores but it is rather a helpful way to help a neglected deployment kit — Obviously they were trying to ditch Theme Kit instead of Slate, but that might not be happening now? If anyone knows please comment! :)</p><p>If you use Shopify everyday or every week like me and you’re a developer then you probably use the Shopify Theme Kit to upload your theme changes via the CLI provided deployment software. (Can be found here: <a href="https://shopify.github.io/themekit/">https://shopify.github.io/themekit/</a>)</p><p>If you are still with us, then you must also have encountered the many PROTOCOL_ERROR or timeouts that come with either the deploy or watch commands, example:</p><pre>livingthedream&gt; theme watch -e=&lt;config.yml theme handle&gt; <br><strong>OR<br></strong>livingthedream&gt; theme deploy assets/logo.png -e=&lt;config.yml theme handle&gt;</pre><p>If its a single request/file deployment, or just a few small files then most of the time your fine, but what if you have 300 files? or 50 files that are all a few mb in size? Then you get a lot of these if your lucky:</p><pre>[development] (assets/logo.jpg) Put <a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">https://******.myshopify.com/admin/themes/</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">**********</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">/assets.json</a>: stream error: stream ID 49; PROTOCOL_ERROR<br>[development] (assets/logo2.jpg) Put <a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">https://******.myshopify.com</a>/admin/themes/<a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">**********</a>/assets.json: stream error: stream ID 45; PROTOCOL_ERROR<br>[development] (assets/logo3.jpg) Put <a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">https://******.myshopify.com</a>/admin/themes/<a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">**********</a>/assets.json: stream error: stream ID 57; PROTOCOL_ERROR<br>[development] (assets/logo5.jpg) Put <a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">https://******.myshopify.com</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">/admin/themes/</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">**********</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">/assets.json</a>: stream error: stream ID 51; PROTOCOL_ERROR<br>[development] (assets/logo8.jpg) Put <a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">https://******.myshopify.com</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">/admin/themes/</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">**********</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">/assets.json</a>: stream error: stream ID 37; PROTOCOL_ERROR<br>[development] (assets/logo24.jpg) Put <a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">https://******.myshopify.com</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">/admin/themes/</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">**********</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">/assets.json</a>: stream error: stream ID 55; PROTOCOL_ERROR<br>[development] (assets/logo201.jpg) Put <a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">https://******.myshopify.com</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">/admin/themes/</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">**********</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">/assets.json</a>: stream error: stream ID 47; PROTOCOL_ERROR<br>[development] (assets/logo234.jpg) Put <a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">https://******.myshopify.com</a><a href="https://vivo-fluid.myshopify.com/admin/themes/4565401644/assets.json">/admin/themes/**********/assets.json</a>: stream error: stream ID 43; PROTOCOL_ERROR</pre><p>This won’t do at all, Shopify’s CDN seems to have issues with anything that is more than very light deployment usage and I have checked with other developers who say they have the same plight — so what can be done?</p><h3>Using the Shopify methods</h3><p>Shopify obviously provide their own ways to help with this issue, the most obvious is the timeout option you can add to your themes in the <strong>config.yml</strong>:</p><pre>development:<br>  password: ***************************<br>  theme_id: &quot;***********&quot;<br>  store: ***********.myshopify.com<br>  timeout: 300s</pre><p>I have it set to 300ms to help minimise the errors but it only helped for a short time and recently it seems to not make any difference because the problems are not with the connection uploading but actually best of both along with Shopify’s oversold/over loaded CDN (I know they buy their CDN from <a href="https://www.fastly.com/">Fastly</a> before anyone tells me they don’t run their own CDN, it has the same result though unfortunately).</p><p>They also introduced the n switch:</p><pre>livingthedream&gt; theme <strong>-n deploy|watch</strong></pre><p>The n switch is used if you want them to not delete the CDN’s copy of a file (if you are re-uploading it or replacing it) until the new file is uploaded, it looks like this was done as the protocol errors and such were meaning people’s original assets disappeared from their theme and if the new one was not completely uploaded then you ended up with no file on your theme. (I could be wrong about this, just an assumption)</p><p>Now unless you want to manually upload every asset, template, section, snippet using either GUI or CLI, then you have to put up with these errors because Shopify tries to parallel throw everything onto its CDN and then in come those pesky protocol errors, so I had enough and decided to make up some bash commands that can be used to feed the files for deployment to Shopify one at a time, you may think this would be slow but actually its surprisingly refreshing to see every single file just go up straight away and although slower than the Shopify recommended route — it works properly!</p><h3>Introducing find</h3><p>If we use a couple of existing CLI tools that are available on pretty much every non-Windows systems and can be installed where they are not, find and xargs. Find does what it says on the tin — it finds files or directories and supports too many switches and options to explain it here, please run the man find command in your CLI environment to get detailed information on your system’s version of find.</p><p>I created these on a MacOS machine, but it should work with the standard find found on Linux systems as well, the GNU version. The switches differ slightly so I have provided two copies of the command to try on your system.</p><p>Xargs is a little more complicated, again its beyond the scope of this article to explain it, so please run man xargs to get local detailed information, the basic premise is it helps to connect the output from a command into the input arguments for another command, add in some switches, a regular expression and you have yourself a custom Shopify deployment command that can deploy files one at a time, recursively, into the 100s without error — just set it going and get more coffee.</p><pre><strong>MacOS:</strong></pre><pre>livingthedream&gt; find -E assets -regex &#39;.*.js|.*main.css&#39; -print0 -type f | xargs -0 -t -n 1 theme deploy -e=&lt;config.yml theme handle&gt;</pre><pre><strong>Linux/Windows/Other Systems:</strong></pre><pre>livingthedream&gt; find assets -regextype posix-extended -regex &#39;.*.js|.*main.css&#39; -print0 -type f | xargs -0 -t -n 1 theme deploy -e=&lt;config.yml theme handle&gt;</pre><pre><strong>Test version of command:</strong></pre><pre>livingthedream&gt; find -E assets -regex &#39;.*.js|.*main.css&#39; -print0 -type f | xargs -0 -t -n 1</pre><pre><strong>Note:<br>The test version omits the theme command, in which case xargs will call &#39;echo&#39; instead and so it will just print out each file it would send to the command - a great way to test what your regex or find expression will be sending to Theme Kit before it actually does - I find this another good plus.</strong></pre><p>If you want to do non-regex find expressions, that will work too just remove -regex and -E switches from your find command and change your expression to be simple wildcard e.g. *.js or an absolute directory/path you want to deploy.</p><p>Remember it will find recursively down from wherever you send it, so be careful of that. You can use the -type f switch to ensure it only tries to send the files to the command and not directories.</p><p>The main switch to explain is the -print0 and the Xargs -0 switch, they must be used in combination in order for xargs to correctly handle special characters like spaces in the filenames. It also condenses find’s output to one line with null characters after each filename, this is better for large recursive lists of directory trees.</p><h3>Rounding Up</h3><p>A very quick &amp; simple solution but I know how many developers battle those PROTOCOL_ERROR messages every week and it can be very frustrating for yourself &amp; your clients/colleagues if updates or deployments scheduled are then just a battle with this out dated tool.</p><p>I hope Shopify start re-developing this or it’s Slate prototype replacement soon! :)</p><p>Stay safe everyone!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feaa2c5d114d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shopify Advanced Previewing: Redirect all non-staff using a quick snippet (Staff-only live…]]></title>
            <link>https://live-the-dreams.medium.com/shopify-advanced-previewing-redirect-all-non-staff-using-a-quick-snippet-staff-only-live-26f34514846a?source=rss-832969f3b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/26f34514846a</guid>
            <category><![CDATA[liquid]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[preview]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[snippet]]></category>
            <dc:creator><![CDATA[Living The Dream]]></dc:creator>
            <pubDate>Sun, 19 Jan 2020 06:45:49 GMT</pubDate>
            <atom:updated>2020-01-19T06:54:28.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>Shopify Advanced Previewing: Redirect all non-staff using a quick snippet (Staff-only live previews of any page or template)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*korOnjBy8ZUN7mFzdMuwQg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@clark_fransa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Arnold Francisca</a> on <a href="https://unsplash.com/s/photos/shopify?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>The Problem</h3><p>If your a Shopify developer or even a Shopify “Expert”, then you’ve had to battle your way round the odd workaround situation due to the limitations of the system — that&#39;s how life is when you work primarily on a platform that is closed off apart from Liquid theme templates containing pre-defined objects and filters, HTML, CSS &amp; JS. This means that a lot of the time, you have to bend stuff round to get Shopify to act how you require it too.</p><p>Recently at the company I work for (A large food supplement Shopify company), we realised that you can have preview themes, but you can’t preview a hidden product on a preview theme — even if you juggle the URLs and parameters around it seems that you can have one or the other. You can either preview a hidden product on the live theme, or preview a non-live theme but without the product.</p><p>We need to carry out mission critical shopping experience updates to our theme &amp; product purchase flow by adding more variant options and then develop a preview theme around the new hidden duplicated products, so we had to come up with a way we could do both so here it is.</p><h3>The Snippet</h3><p>All we need to do is use a bit of a workaround and make it includable on any page we want that is live on the live theme, that will redirect the user before the page is displayed. I called it <strong>is-admin.liquid </strong>but you can call it is-staff.liquid or whatever makes most sense.</p><p>The snippet itself explains how it works in the top comment, but basically it looks for the preview theme bar that shows up on every page load if your previewing a theme, this allows you to have a live product that is a duplicate with new data and simply do:</p><pre>{% include &#39;is-admin&#39; %}</pre><p>The snippet has to use some questionable technique to work round Shopify and how it processes the header data for its own JS, so we use its <strong>capture </strong>method<strong> </strong>to capture the<strong> content_for_header</strong>, the way I designed it is so it can be used anywhere on a page, but that does mean <strong>content_for_header</strong> gets processed twice, the best case scenario would be to include the snippet in the header of every page and echo the <strong>content_for_header</strong> where it has been captured — this way you would only have to have Shopify process your header only once but for most stores and developers this shouldn’t really be much of a concern.</p><p>Including the snippet anywhere in the page should be alright, but your best off getting it as close to the top of the page as possible — so the redirect is called before the page starts to fully render, the choice we made is to just direct them to the standard 404 page but another choice is sending them back to the homepage. You could even use a flash notice to notify your users that part of your site is still under construction, this will also work for Collections, Pages, any Shopify template type basically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/386b8728961290f8411d88e100600bd5/href">https://medium.com/media/386b8728961290f8411d88e100600bd5/href</a></iframe><p>Now at the time of writing, this is how Shopify inject their preview bar as explained in the Gist. As it says Shopify can at any time change the way they inject the bar, rename objects or references used or any change could essentially break this method — you will then have to track down the change and modify the part of the snippet that uses the <strong>contains </strong>operator to get it working again.</p><p>Shopify is a great platform, but it has its limitations and sometimes even with the minor performance hit you’ll get from this snippet, it&#39;s better than having your preview-live hybrid development available for anyone/any search engine to see.</p><h4>Things to remember</h4><ol><li>Make sure you only ever include the snippet on a page once, including it more than once will decrease performance further and not actually help in any way apart from confusing the browser further.</li><li>Keep checking the code works and Shopify haven’t modified anything — this is not built for long term production use but more for short term sprints where there is no other option due to needing to use live data but hide it from non-staff.</li><li>Make sure anyone you do want to view it gets provided the correct preview link and they use it before they try to visit the hidden page, a common mistake you wouldn’t believe!</li><li>Try get the snippet as high as you can up the page, so it fires before the page starts building itself out.</li><li><em>Please make sure you don’t have a link to the hidden page floating around in a loop of collections or the main menu, another surprising common oversight.</em></li><li>Once included on the page, you can also use &amp; test the isAdmin variable that has been assigned to true, just in case you wish to use it for non-redirect reasons, this snippet can easily be modified to carry out another action such as flashing a notice, changing how the page renders or anything you can come up with! <strong>Get creative now you can tell whos a staff member or not.</strong></li></ol><h4>Little Advanced Tip</h4><p>If you have no choice but to use this workaround for a while, consider adding support for the search engine noindex meta tag like below, which will also help disguise people from ending up on pages they shouldn’t be on anyway.</p><pre><strong>All Engines:</strong><br>&lt;meta name=&quot;robots&quot; content=&quot;noindex&quot; /&gt;</pre><pre><strong>Specifically Google:</strong><br>&lt;meta name=&quot;googlebot&quot; content=&quot;noindex&quot; /&gt;</pre><p>Right, I hope you guys have good luck hiding your new exciting development from the world until they are ready to see it!</p><p>If you require Shopify help, use their Expert program or email myself at root@ livingthedream.fun and I can direct you to recommended Shopify developers with many years experience.</p><p>Its now 2020 as well, happy new year!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26f34514846a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Command Line Tools to Aid Development — Part 3 (Linting)]]></title>
            <link>https://live-the-dreams.medium.com/using-command-line-tools-to-aid-development-part-3-linting-a6033e70e6fe?source=rss-832969f3b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6033e70e6fe</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[linter]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[linting]]></category>
            <dc:creator><![CDATA[Living The Dream]]></dc:creator>
            <pubDate>Tue, 10 Dec 2019 14:47:08 GMT</pubDate>
            <atom:updated>2019-12-10T14:47:08.025Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Command Line Tools to Aid Development — Part 3 (Linting)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-OYMaigFVPyv_hMKAs8KQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@averieclaire?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">averie woodard</a> on <a href="https://unsplash.com/s/photos/tumble-dryer-lint?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Part 3 of this series takes us away from quick text processing to a bigger concept.</p><h3>What is linting?</h3><p><em>No, don’t print your code off and stick it in the tumble dryer.</em></p><p>Taken from Wiki, the definition of software linting is as follows:</p><blockquote><strong>Lint</strong>, or a <strong>linter</strong>, is a tool that analyzes <a href="https://en.wikipedia.org/wiki/Source_code">source code</a> to flag programming errors, <a href="https://en.wikipedia.org/wiki/Software_bug">bugs</a>, stylistic errors, and suspicious constructs.<a href="https://en.wikipedia.org/wiki/Lint_%28software%29#cite_note-1">[1]</a> The term originates from a <a href="https://en.wikipedia.org/wiki/Unix">Unix</a> <a href="https://en.wikipedia.org/wiki/List_of_utility_software">utility</a> that examined <a href="https://en.wikipedia.org/wiki/C_(programming_language)">C language</a> source code.<a href="https://en.wikipedia.org/wiki/Lint_%28software%29#cite_note-BellLabs-2">[2]</a></blockquote><p>So the idea behind it is fairly basic to understand, its a tool you can use to analyse your source code (before compilation/interpretation) to enforce good coding practice, find potential bugs, correct/flag styling issues etc.</p><p>When the first lint program was created it was all about coding in C or similar compiled languages. Nowadays the pool of different languages &amp; paradigms is much larger — so what if you want to lint your Node.js server source? or your Python Machine Learning model? Or the new crate you want to publish in Rust?</p><p>Luckily, most modern languages all have a de-facto linter packing their own language specific rulesets and I will first explain a bit about how linters usually work then I will show an example from a very popular language &amp; a list of the most popular linters for most modern day languages.</p><h3>A little wooly history</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Z9IiCCjlYtAwZZLlvZNVA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@glorain?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Guillaume LORAIN</a> on <a href="https://unsplash.com/s/photos/wooly-lint?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Linting was first introduced in the 1980s (by <a href="https://en.wikipedia.org/wiki/Stephen_C._Johnson">Stephen C. Johnson)</a> for the original Unix operating system, so the concept is an old one. Now after some time the C/C++ compilers caught up by introducing lint-like rules into the compiling stage to help people with less need for the external tool. (<em>See end of article!)</em></p><p>Linters had to get more creative as languages evolved at an extreme rate, by the time we made it to 2000 (&amp; beyond!) they started introducing the functionality we see today that even help you name variables &amp; indent your code properly. When interpreted languages such as Perl, Python, Ruby etc became very popular there was even more need to ‘lint’ source code because the compiling stage was no longer needed before execution — meaning that you would skip the part of the development process that tells you about possible warnings/errors that will occur during runtime.</p><p>Despite this many developers today do still not know about the many command-line based linting tools that exist for 99% of languages. Even more so some developers have their code linted automatically by build processes, packers (<a href="https://webpack.js.org/">Webpack</a> is a lovable offender) and such without even realising what they do in the background. So whichever camp your in, you should know about this stuff.</p><h3>How does it work?</h3><p>A real quick breakdown of how linting works:</p><ul><li>It opens each code file one-by-one.</li><li>It goes down the file usually line-by-line. (It also parses language specific stuff like indents, functions, code blocks, loops etc for multi-line applicable rules)</li><li>Each line gets parsed and checked against ‘rulesets’</li><li>The rulesets are configurable to your liking/standards and usually are stored in configuration/markup files that contributors come up with containing all sorts of rules such as code styling, naming conventions, unused variables, runtime errors etc.</li><li>If a line matches a rule, it is logged by the linter with its file/line location and the rule it triggered.</li><li>After all the code you specified or the whole project has been ‘linted’, the results are displayed to you usually then &amp; there with the required information to go find every rule or style break and fix them up — alternatively you can let certain implementations loose and allow auto-fixing in-place or in new file copies.</li><li>Results can be made into reports for large projects or codebases that need extensive review usually in common formats like HTML, XML &amp; JSON.</li><li>Most implementations will support a variety of in-code or in-project/global configuration for ignoring the odd line or the entire project with certain warnings or errors, useful for the exceptions to the rules.</li></ul><p>This should be enough of an explanation for you to understand the language specific example I’ll get into now, it&#39;s not necessary to get into the depths of how they really crawl the code as that can change per language as well depending on if its compile or “onsave” methods parsing the files.</p><h3>Lets get linty</h3><p>For the first example I’ve chosen the most popular language at this point in time — Javascript. Everyone knows Javascript and now it has server side capabilities and frameworks for UI such as <a href="https://reactjs.org/docs/thinking-in-react.html">React.js</a>, <a href="https://angular.io/">Angular.js</a> and <a href="https://vuejs.org/">Vue.js</a> it has become unstoppably popular among front &amp; back &amp; full stack developers in recent years.</p><p>Some of these modern JS frameworks actually enforce code linting without you really noticing unless you know what it is — we will do an example using the current most popular JS linter which is <a href="https://eslint.org/">ESLint</a>.</p><blockquote>ESLint is an open source project originally created by <a href="http://nczonline.net/">Nicholas C. Zakas</a> in June 2013. Its goal is to provide a pluggable linting utility for JavaScript.</blockquote><p>ESLint is used by frameworks such as React.js to automatically keep your code in check, it has full support for the JSX variant to help even further.</p><p>First off you better have it installed, its readily available on NPM and its best to have it globally installed so you can easily use it to check any code in any project.</p><h4>Locally (Recommended):</h4><pre>livethedream$ npm install eslint --save-dev<br><br># or<br><br>livethedream$ yarn add eslint --dev</pre><h4>Globally:</h4><pre>livethedream$ npm install -g eslint<br>/usr/local/bin/eslint -&gt; /usr/local/lib/node_modules/eslint/bin/eslint.js<br>+ eslint@5.16.0<br>added 117 packages from 70 contributors in 8.917s<br>livethedream$</pre><p>Once that has completed, you should be able to run it and see its options.</p><pre>livethedream$ eslint --help<br>eslint [options] file.js [file.js] [dir]</pre><pre>...lots of options here...</pre><p>It will print out its full set of command line options, but that only scratches the surface of this modular wonder of enforced code perfection. It is mainly configured by the use of .eslintrc files either in the directory or globally depending on how you installed it earlier in the process.</p><p>If you installed it locally as a development dependency then you can run it anytime using npx:</p><pre>livethedream$ npx eslint --init<br><strong>^</strong> This creates your local .eslintrc file.</pre><pre>livethedream$ npx eslint file.js<br><strong>^</strong> This runs the linter on the specified file.</pre><pre>livethedream$ eslint --init <br><strong>^ </strong>Everything after the command is the same global or not, you can just remove npx prefixing if you have it globally installed.</pre><p>When you run eslint init, it asks you a set of questions &amp; criteria to specify and then it generates your file, 90% of cases you will only need to do this once and never dig into the files themselves unless you have to customise one of the very popular existing rulesets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zsDbmYosmbiPtVjZUpLEag.png" /><figcaption>eslint — init</figcaption></figure><p>After the ‘core’ ruleset always included by default, the other three main rulesets for ESLint are <a href="https://github.com/airbnb/javascript">Airbnb</a>, <a href="https://github.com/standard/standard">Standard</a> and <a href="https://github.com/google/eslint-config-google">Google</a>, both maintained to a high standard at the time of writing, your in capable hands with all of them and of course you can modify the rulesets or ignore certain rules and tweak until your heart’s content. They are designed to drop on top of the default set to create the final base rules, focusing more on style &amp; convention than actual errors.</p><blockquote>ESLint and most Linters worth their Wool (<em>I know, lame</em>) support .eslintignore files that you can use in the exact same fashion as .gitignore to specify list of files/directories to not be parsed under &amp; in the directory the ignore file is placed.</blockquote><p>Right, you’ve installed &amp; initialised your environment, setup your npm project for linting and presumably you’ve got some code to be parsed, lets see what happens if we purposely wind up ESLint.</p><p>Let’s take a look at a simple example of it in action, using the Google ruleset and Node as the target environment. I made a quick file <em>lintme.js</em>:</p><pre>const lintMePlease = () =&gt; {<br>  console.log(&#39;LINT ME&#39;);<br>}</pre><p>If you just paste this in your browser’s Javascript console, it would cleanly be accepted in any modern browser that supports arrow functions and const (ES6+ ECMA spec) — but linters don’t just fix errors in code, they also enforce styling &amp; convention based on the rulesets which by design can be rather strict.</p><p>Lets run ESLint and see the output, I generated an image showing the output so I could show how ESLint formats &amp; colours its output in your console to make it easier to read and get the jist of the results.</p><pre>livethedream$ npx eslint lintme.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_v-XzzO2LWtlix_5j7gk6w.png" /><figcaption>Linters usually format their output as best as possible in the terminal, or even generate output files in formats such as HTML, XML &amp; JSON.</figcaption></figure><p>It is best to run Linters without fixing on your first runs to correct everything you want to correct manually first, to set ignores for any specific use cases you can’t change and the like — then you can take advantage of the fix option to in-place edit the code as it goes fixing what it can from its rulesets.</p><pre>livethedream$ npx eslint --help<br>Fixing problems:<br>--fix                          Automatically fix problems<br>--fix-dry-run                  Automatically fix problems without<br>saving the changes to the file system<br>--fix-type Array               Specify the types of fixes to apply (problem, suggestion, layout)</pre><pre>livethedream$ npx eslint --fix lintme.js<br>lintme.js<br>1:7  error  &#39;lintMePlease&#39; is assigned a value but never used  <em>no-unused-vars</em><br><strong>✖ 1 problem (1 error, 0 warnings)</strong></pre><pre>livethedream$</pre><p>It automatically fixed the semicolon error which is an easy one of course, but it has to leave the no-unused-vars error because it cannot make up logic or code only refactor, optimise &amp; style existing code.</p><h3>Using Ignores</h3><p>Let’s see how we can use ignores to make the file pass the final check of the file, there is a massive list of all the usual code level problems in the default ESLint ruleset (separate to the selected 3rd party Github repository rules you chose during init) page <a href="https://eslint.org/docs/rules/">here</a>. It denotes which can be fixed automatically and which require manual modification, sometimes though you just need to turn off one rule for one line, block, file or folder of a project, which is where ignores come in.</p><p>ESLint and most popular linters allow certain comments or directives to disable XYZ for N lines or files etc, this is our new file now using <em>eslint-disable-next-line </em>to ensure it now passes along with its already in-place fixed semicolon.</p><pre>// eslint-disable-next-line<br>const lintMePlease = () =&gt; {<br>  console.log(&#39;LINT ME&#39;);<br>};</pre><p>This results in no output, which for linting is good news meaning it passed all its checks and fixed anything it was configured too by default!</p><p>I know this guide concentrates solely on ESLint in the examples, but I created it as more of a general guide that had to be kept short and so I chose the Linter that was most popular installed on people’s editors on the current most popular language (Javascript) to target the largest amount of people — while keeping in mind that all the concepts explained and the examples all follow the basic principles of how these programs execute and how they are operated. With documentation you will be able to adapt the theory to any language/linting combination.</p><h3>Getting Linty in your editor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPaDLqRbIlQybDsEc5deIg.jpeg" /><figcaption>Sublime Text Editor | Photo by <a href="https://unsplash.com/@ilyapavlov?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ilya Pavlov</a> on <a href="https://unsplash.com/s/photos/text-editor?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I have recently converted fully to <a href="https://code.visualstudio.com/">Visual Studio Code</a> for my editor and it has fantastic support in its plugins library for all the primary linters for each language you could think of. Once I had ESLint installed globally by npm it was only a couple of clicks to get VSCode running all .js files through ESLint upon save using the .eslintrc files in workspace folders as well, allowing for the typical customisation without limits.</p><p>Other editors like <a href="https://www.sublimetext.com/">Sublime Text</a> &amp; <a href="https://atom.io/">Atom</a> also have good support for popular language/linter combinations through their own community supported plugin &amp; package systems — you’d be lucky to find a language &amp; linter that you can’t automatically setup in your preferred environment in just a few minutes.</p><p>Make sure your editor’s formatting package is prepared to work alongside the re-formatting carried out by the Linter, a common combination is ESLint and <a href="https://prettier.io/">Prettier</a> formatter on VSCode.</p><h3>Getting Linty at compile-time</h3><p>With modern compilers such as the standard Rust &amp; Go compilers or modern C++ compilers (especially commercial ones) include linting in the functionality of the compiler — they also can help catch errors, memory leaks or other possible runtime issues.</p><p>It&#39;s not unheard of to run code through a 3rd party strict ruleset first to enforce your own higher level guidelines and then compile-time rulesets as standard with the compilation process.</p><h3>Getting Pipe-Linty</h3><p>As a quick bonus, I will cover how you can easily pipe from any command straight into ESLint and have it fix in-place before returning the code to the stdout output (so it can be piped on further instead of being written to a file), ESLint specifies the use of the following options to achieve it, creating a pipe’d JSON object reporting the findings and new code:</p><pre>livethedream$ cat lintme.js | eslint --stdin --fix-dry-run --format=json | python -m json.tool<br>[<br>  {<br>    &quot;errorCount&quot;: 1,<br>    &quot;filePath&quot;: &quot;&lt;text&gt;&quot;,<br>    &quot;fixableErrorCount&quot;: 0,<br>    &quot;fixableWarningCount&quot;: 0,<br>    &quot;messages&quot;: [<br>      {<br>        &quot;column&quot;: 7,<br>        &quot;endColumn&quot;: 19,<br>        &quot;endLine&quot;: 1,<br>        &quot;line&quot;: 1,<br>        &quot;message&quot;: &quot;&#39;lintMePlease&#39; is assigned a value but never used.&quot;,<br>        &quot;nodeType&quot;: &quot;Identifier&quot;,<br>        &quot;ruleId&quot;: &quot;no-unused-vars&quot;,<br>        &quot;severity&quot;: 2<br>      }<br>    ],<br>    &quot;output&quot;: &quot;const lintMePlease = () =&gt; {\n  console.log(&#39;LINT ME&#39;);\n};\n&quot;,<br>    &quot;warningCount&quot;: 0<br>  }<br>]</pre><h3>Linted List</h3><p>Here is a handy list I’ve made up of each popular modern language and its associated most popular linter(s) (up to 3):</p><ul><li><strong>Javascript:</strong> <a href="https://eslint.org/">ESLint</a>, <a href="https://github.com/douglascrockford/JSLint">JSLint</a>, <a href="https://jshint.com/about/">JSHint</a></li><li><strong>Python: </strong><a href="https://www.pylint.org/">Pylint</a>, <a href="https://www.jetbrains.com/help/pycharm/code-inspection.html">PyCharm</a>, <a href="http://flake8.pycqa.org/">Flake8</a></li><li><strong>Java: </strong><a href="http://checkstyle.sourceforge.net/">Checkstyle</a>, <a href="https://pmd.github.io/">PMD</a>, <a href="https://spotbugs.github.io/">Spotbugs</a></li><li><strong>PHP: </strong><a href="https://cs.symfony.com/">PHP Coding Standards Fixer</a>, <a href="https://phpmd.org/">PHP Mess Detector</a>, <a href="https://github.com/nanch/phpfmt_stable">PHPfmt (Sublime Editor Plugin)</a></li><li><strong>Rust: </strong><a href="https://github.com/rust-lang/rust-clippy">Rust Clippy</a>, <a href="https://doc.rust-lang.org/rustc/lints/index.html">RustC (Compiler)</a></li><li><strong>Go: </strong><a href="https://github.com/golang/lint">Golint</a>, <a href="https://github.com/mgechev/revive">Revive (Golint fork/replacement)</a></li></ul><p>Thank you for listening to all my ranting, I hope this new part of my old series will help at least someone out there! Feel free to provide feedback or email me at root @ livingthedream.fun — I am currently working fulltime as a lead developer again but I wish to get back into article writing more often and I am openly looking for a Medium Publication if anyone sees this and thinks I’d be a good fit.</p><blockquote><strong>Happy Linting!</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6033e70e6fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Express.js/Node TradeGecko Webhook Verification (REST API/Gist)]]></title>
            <link>https://live-the-dreams.medium.com/quick-express-js-node-tradegecko-webhook-verification-rest-api-gist-5109673e3836?source=rss-832969f3b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/5109673e3836</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tradegecko]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Living The Dream]]></dc:creator>
            <pubDate>Mon, 11 Nov 2019 09:31:01 GMT</pubDate>
            <atom:updated>2019-11-11T09:31:01.313Z</atom:updated>
            <content:encoded><![CDATA[<p>While looking myself for a pre-built or pre-answered (e.g. Stack Overflow) answer to verifying the X-Gecko-Signature header that is passed in the HTTP request of all the TradeGecko Webhook events — I couldn’t find one!</p><p>Usually for such a simple thing, you know 300 other people have asked your exact question or used the same setup to do the same thing and shared the code, when your working trying to maximise the progress per hour, things like this are easier to look up, test and just credit source in your code so you can get on with interfacing with the API.</p><p>I do know there is a TradeGecko Node module, but it doesn’t mention Webhooks, only the standard REST endpoints and I had already been using the request module for another API and I just kept on using it for pushing GET, POST, PUT &amp; DELETE to TradeGecko, all it requires is a simple key in the request header just like its incoming counterpart.</p><p>The example was a Ruby one-liner that wasn’t very well documented, as most of the TG API isn’t well explained just a bunch of endpoints and then some cURL terminal commands or Ruby for the Rails crowd being the example options etc. The main things we need to know about Webhooks are well explained like the points on processing async and such:</p><blockquote>Responding to a webhook</blockquote><blockquote>When receiving a webhook, the request must complete within a 10-second window, we highly recommending processing the webhooks asynchronously to avoid any problems.</blockquote><blockquote>We use HTTP response codes to determine whether a webhook has been received successfully. If your server returns a HTTP status code between 200 and 399, we assume it has been processed successfully.</blockquote><blockquote>A HTTP 410 Gone response will automatically delete the webhook.</blockquote><blockquote>Other responses will cause the outgoing request to be retried, based on an <a href="https://github.com/mperham/sidekiq/wiki/Error-Handling#automatic-job-retry"><strong>exponential backoff strategy</strong></a>.</blockquote><blockquote>If we receive unsuccessful responses consecutively for 3 days, the webhook will be deleted. Any successful response within the 3 day period will reset the counter. Application developers will receive daily emails to notify them of webhook failure and webhook deletion.</blockquote><p>This gives us solid info on how we must respond immediately to their API, and then process our data after that — whether the Webhook data is used or not should be calculated differently to whether it is verified and a successful HTTP request or not.</p><p>Anyway here it is, just a very quick non-optimised, ‘let&#39;s get this Webhook verifying’ snippet/function you can deploy in your Node.JS or Express.JS app — if you don’t use Express as your framework or you don’t even use a framework, its very easy for you to convert this function to work as a normal Javascript async function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d79f4598f8882f1841d093da53ce434/href">https://medium.com/media/8d79f4598f8882f1841d093da53ce434/href</a></iframe><p>I hope this helps people who are in the position I was in on the weekend, needing a quick function to speed up the day’s development and now you have found it.</p><p>Here is some links to the different working parts involved/pages I had to read.</p><p>(<strong>Documentation for TradeGecko Webhooks: </strong><a href="https://developer.tradegecko.com/docs.html#webhooks">https://developer.tradegecko.com/docs.html#webhooks</a>)</p><p>(<strong>Express.js:</strong> <a href="https://expressjs.com/">https://expressjs.com/</a>)</p><p>(<strong>raw-body Node module:</strong> <a href="https://www.npmjs.com/package/raw-body">https://www.npmjs.com/package/raw-body</a>)</p><p>(<strong>Node native built-in Crypto module:</strong> <a href="https://nodejs.org/api/crypto.html">https://nodejs.org/api/crypto.html</a>)</p><p>(<strong>Node itself, if you have been living under a rock:</strong> https://nodejs.org)</p><p>Enjoy! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5109673e3836" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the f*ck is a Snuffleupagus?]]></title>
            <link>https://live-the-dreams.medium.com/what-the-f-ck-is-a-snuffleupagus-f838fb64f857?source=rss-832969f3b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/f838fb64f857</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[snuffleupagus]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[suhosin]]></category>
            <dc:creator><![CDATA[Living The Dream]]></dc:creator>
            <pubDate>Fri, 19 Apr 2019 11:27:29 GMT</pubDate>
            <atom:updated>2019-04-19T11:27:29.958Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AyvZChrhJJ4JOCly5NMnQg.jpeg" /><figcaption>intPhoto by <a href="https://unsplash.com/photos/flha0KwRrRc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nahel Abdul Hadi</a> on <a href="https://unsplash.com/search/photos/hacker?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Ever wonder what happened to PHP Suhosin?</p><p>We all remember the great days of the <a href="https://suhosin.org/stories/index.html">Suhosin</a> patch &amp; extension for PHP, finally the language that runs so much of our web getting some much needed core security, meaning more hosts could sleep at night knowing their users were not totally exposing them at application level. I will just go through the basic premise again for those who missed out first time round.</p><h4>The patch</h4><p>First off the Suhosin ‘patches’ the core PHP engine, allowing it to fix such vulnerabilities like buffer overflows at the low level, this led to even some *nix distros shipping their PHP with the patch already applied and web hosting panels to adopt it too.</p><p>Here is a list of some of the patch benefits taken from their own site:</p><ul><li>Protects the internal memory manager against buffer overflows with Canary and SafeUnlink Protection</li><li>Protects Destructors of Zend Hash-tables</li><li>Protects Destructors of Zend Linked-Lists</li><li>Protects the PHP core and extensions against format string vulnerabilities</li><li>Protects against errors in certain libc realpath() implementations</li></ul><h4>The extension</h4><p>The extension has a lot more to it, this not only focuses on fixing/protecting the core PHP implementation but the key bit is how it protects applications because so much widely used PHP projects such as CMS like Wordpress, Joomla (lets face it Joomla was terrible for security!), Drupal etc — they were all racking up a seriously impressive amount of security vulnerabilities from the trivial to the “just let yourself in, sir” kind.</p><p>Suhosin allowed you to enable/disable certain rules and rulesets just like a firewall that would allow/disallow certain suspicious or unsafe function calls, operations, ini_set changes and such so that you could tweak the security of any code running in your PHP environment regardless of website or user.</p><p>This was especially useful when major very popular exploits would surface — meaning you could update your Suhosin rules to temporarily fix the execution of the malicious attack until all your users got round to updating their software or patching their own code. This was a godsend for shared hosting companies.</p><p>Here is some major features listed for the extension:</p><ul><li>Transparent Cookie Encryption :!:</li><li>Protects against different kinds of (Remote-)Include Vulnerabilities</li><li>Disallows Remote URL inclusion (optional: black-/whitelisting)</li><li>Disallows inclusion of uploaded files</li><li>Optionally stops directory traversal attacks</li><li>Allows disabling the preg_replace() /e modifier</li><li>Allows disabling eval()</li><li>Protects against infinite recursion through a configurable maximum execution depth</li><li>Supports per Virtual Host / Directory configurable function black- and whitelists</li><li>Supports a separated function black- and whitelist for evaluated code</li><li>Protects against HTTP Response Splitting Vulnerabilities</li><li>Protects against scripts manipulating the memory_limit</li><li>Protects PHP‘s superglobals against extract() and import_request_vars()</li><li>Adds protection against newline attacks to mail()</li><li>Adds protection against 0 attack on preg_replace()</li></ul><p>That&#39;s just some of the main options and protections this Suhosin offers.</p><h3>The problem?</h3><p>Now you&#39;re wondering why I am notifying you all of something that has been around a long time, we get finally to: <strong>the problem</strong>.</p><p>Suhosin does not properly support PHP7. Now you might be about to comment with the link to the Suhosin PHP7 development repo, I’ll do that for you: <a href="https://github.com/sektioneins/suhosin7">https://github.com/sektioneins/suhosin7</a></p><p>You will notice that nothing has been updated in ‘3 years’ and the notice at the beginning reads:</p><blockquote>WARNING: THIS SOFTWARE IS PRE-ALPHA SOFTWARE. DO NOT ATTEMPT TO RUN IN PRODUCTION</blockquote><p>Suhosin seems to have stalled development for a long time, leaving hosts/admins that want to use it stuck offering only PHP5 installations. This is now getting a bigger problem since PHP released 7.3, adoption of the many new features now forcing a wider backwards-compatible gap. CMS giants are now starting the haul to full PHP7 times, gradual typing is becoming popular rather than shunned.</p><p>I did some research and read forum posts where certain popular pieces of software have lost actual amounts of users because they are limited to PHP5 still because of Suhosin.</p><h3>The solution: A Snuffle-what-amus?</h3><p><a href="https://snuffleupagus.readthedocs.io/">snuffleupagus</a> might just be the rescue your after from these dark exploitable times.</p><blockquote>Snuffleupagus is a <a href="http://php.net/manual/en/migration70.php">PHP7+</a> module designed to drastically raise the cost of attacks against websites. This is achieved by killing entire bug classes and providing a powerful virtual-patching system, allowing the administrator to fix specific vulnerabilities without having to touch the PHP code.</blockquote><p>Snuffleupagus is rapidly becoming the Suhosin for PHP7. It supports up to 7.3, has fairly active development and it works for production environments. It works purely as an extension, so no need to patch your PHP core.</p><p>It provides some decent documentation on its uses, limitations and how to write the <a href="https://snuffleupagus.readthedocs.io/config.html">configuration file</a> for your exact needs — using its intuitive PHP style configuration format that allows for easy virtual-patching of functions. This allows for the same fixing of application level attacks environment-wide.</p><p>Here is some example lines from their default provided config file:</p><pre><em># Harden the PRNG</em><br>sp.harden_random.enable();<br><br><em># Disabled XXE</em><br>sp.disable_xxe.enable();</pre><pre><em># Harden the `chmod` function</em><br>sp.disable_function.function(&quot;chmod&quot;).param(&quot;mode&quot;).value_r(&quot;^[0-9]{2}[67]$&quot;).drop();<br><br><em># Prevent various `mail`-related vulnerabilities</em><br>sp.disable_function.function(&quot;mail&quot;).param(&quot;additional_parameters&quot;).value_r(&quot;<strong>\\</strong>-&quot;).drop();<br><br><em># Since it&#39;s now burned, me might as well mitigate it publicly</em><br>sp.disable_function.function(&quot;putenv&quot;).param(&quot;setting&quot;).value_r(&quot;LD_&quot;).drop()</pre><p>As you can see, it really allows you to change the behaviour of functions at runtime and to disable/enable their use based on multiple properties at their time of calling. It also enables various attack vector fixes such as hardening unserialize() method by using HMAC verification and hardening cookies to stop cookie hijacking.</p><p>If this hasn’t sold you into utilising Snuffleupagus yet, I am sure PHP7 will eventually force you away from Suhosin — a project that seems never to reach the updated compatibility. Just incase though I will leave the installation quick-start instructions here:</p><pre>git clone https://github.com/nbs-system/snuffleupagus<br>cd snuffleupagus/src<br>phpize<br>./configure --enable-snuffleupagus<br>make<br>make install</pre><p>Make sure to read the full documentation &amp; test your rulesets properly before deploying in a production environment!</p><p>A special thanks goes out to Suhosin and Snuffleupagus for helping keep PHP a safer engine for many admins for years :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f838fb64f857" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Command Line Tools to Aid Development — Part 2 (Sed)]]></title>
            <link>https://live-the-dreams.medium.com/using-command-line-tools-to-aid-development-part-2-sed-228d462d3dda?source=rss-832969f3b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/228d462d3dda</guid>
            <category><![CDATA[replace]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[de]]></category>
            <category><![CDATA[gnu]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Living The Dream]]></dc:creator>
            <pubDate>Wed, 03 Apr 2019 12:06:27 GMT</pubDate>
            <atom:updated>2019-04-03T12:06:27.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oT0-Tqda8sGMdKH0SHPbOw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/QQ9LainS6tI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nate Grant</a> on <a href="https://unsplash.com/search/photos/text-files?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Using Command Line Tools to Aid Development — Part 2 (Sed)</h3><p><em>The first part of this series of articles is </em><a href="https://medium.com/@live_the_dream/using-command-line-tools-to-aid-development-part-1-grep-bc9df65a2afe"><em>here</em></a><em> and I recommend you start with that one to get an idea of this series of articles and why using command line tools to aid your development (in any language/environment) can be very useful.</em></p><p>I am going to dive right in here with another text based tool called ‘sed’. Sed stands for ‘stream editor’ and it is another very early Unix days tool created in 1974, its goal being a streams based implementation of text editing that utilises regular expressions which back then was a new era for efficiently processing text. I do consider these articles to at least assume some knowledge/use of regular expressions in any environment prior, explaining regular expressions is beyond the scope of these use cases/tool tutorials and because they are aimed at developers I think it’s safe you would know what they are.</p><p>These days GNU have their own offering of sed which has become the standard edition, this version includes some big improvements and new features including editing files in-place and other functionality for convenience. This package is default available on most Unix/Linux distros, as well as MacOS and can be installed for use on Windows based setups as well.</p><p>Once you have made sure it is available on your chosen development environment you can use sed for various operations that would take longer or be tedious if you were doing it manually or using GUI tools to accomplish. I will show examples of some of these situations for you below.</p><p>I am using sed on MacOS, which it has installed by default, most versions will operate the same for most use cases with the same switches &amp; functionality.</p><pre>livethedream$ sed <br>usage: sed script [-Ealn] [-i extension] [file ...]<br>sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...]<br>livethedream$</pre><p>In modern programming there is a big emphasis on splitting your projects/scripts/programs into multiple neatly organised files that are in various formats and structures in order to keep your project to standards, make it easier for other developers to read &amp; modify, for compiler rules etc. This can mean you end up needing to replace certain words, phrases, variable names and the like project-wide or folder-wide in order to update name changes and such. Sed can help you handle situations like this with ease.</p><h3>Giving commands to Sed</h3><p>On the most basic level, sed takes ‘commands’ in the form of regular expressions, these different commands denote how it will use/behave with the provided expressions. The most used command is substitute, this provides find/replace style functionality.</p><p>Remember like most regular expression engines, you can use flags like /g for global or ‘greedy’ expressions which will perform the match for every occurrence rather than the first one it finds. /I is for ignoring case (<strong>Note:</strong> MacOS/BSD shipped version of sed is missing the ignore case switch among a couple of other more modern features that the GNU one has).</p><p>You can also use different delimiters which is handy especially if your doing operations involving filenames, like this example:</p><pre>livethedream$ sed &#39;s_/usr/bin_/usr/local/bin_/gI&#39; &lt;filename&gt;</pre><h4>Specifying locations</h4><p>If you want to be more specific on where in the file(s) the operations are carried out, you can tell sed line numbers or line number ranges to operate on and even do the same with pattern matches:</p><pre>livethedream$ sed &#39;3 s/&lt;find&gt;/&lt;replace&gt;/&#39; &lt;filename&gt;<br><strong>^</strong> <em>Only match on line 3, </em><strong><em>Note:</em></strong><em> it treats line 1 as line 1, not 0 like some environments.</em></pre><pre>livethedream$ sed &#39;3,10 s/&lt;find&gt;/&lt;replace&gt;/&#39; &lt;filename&gt;<br><strong>^</strong> <em>Only match on lines 3 to 10</em></pre><pre>livethedream$ sed &#39;/^#/ s/&lt;find&gt;/&lt;replace&gt;/&#39; &lt;filename&gt;<br><strong>^</strong> <em>Only operates on lines that start with a #, so comments in certain languages in this instance.</em></pre><pre>livethedream$ sed &#39;/first/,/last/ s/&lt;find&gt;/&lt;replace&gt;/&#39; &lt;filename&gt;<br><strong>^</strong> <em>Only operates on lines between the lines that say first and last. Here&#39;s a working example where any line between the two range pattern lines are deleted using the d command:</em></pre><pre>livethedream$ cat file.txt<br>one<br>first<br>two<br>three<br>last<br>four<br>livethedream$ sed &#39;/first/,/last/ d&#39; file.txt<br>one<br>four<br>livethedream$</pre><h4>Using your matches with &amp; and \1</h4><p>If you want to use part of your matched input in your replacement or command, you can either use &amp; to use the entire matched pattern per line or \1 up to \9 for different grouped parts. Here’s a couple of examples:</p><pre>livethedream$ echo &#39;hello-world-123456789&#39; | sed &#39;s/[a-z\-]*/&amp;/&#39;<br>hello-world-123456789</pre><pre><strong>^</strong> <em>The use of &amp; in the second expression means anything matched in the line/stream pattern will be re-used to define how the second regular expression is carried out.</em></pre><pre>livethedream$ echo &#39;hello-world-123456789&#39; | sed &#39;s/\([a-z\-]*\).*/\1/&#39;<br>hello-world-<br>livethedream$</pre><pre><strong>^</strong> <em>You can see here that creating a group in the first regular expression using \(&lt;group&gt;\) means that the groups get a number starting at \1 and going up to \9 maximum that you can re-use the group in the second expression. The group here is told to match characters a-z in lowercase and the character -, this means it will ignore the numbers at the end and store everything before in \1 for later use.</em></pre><pre>livethedream$ echo &#39;hello world&#39; | sed &#39;s/\([a-z]*\) \([a-z]*\)/\2 \1/&#39;<br>world hello<br>livethedream$</pre><pre><strong>^</strong> <em>This is a common example where two words can be switched round using the grouping references.</em></pre><p>This sort of expansion to the commands gives a lot more power once you start to master them.</p><h4>Chaining commands &amp; Command files</h4><p>Once you get the hang of some basic sed commands you can use some of the switches to chain commands, store commands in sed ‘script’ files etc, here is some examples of more advanced switches. The -e switch can be used for chaining commands to sed, this is also sometimes used by people for single command calls due to personal preference/clarity.</p><pre>livethedream$ sed -i -e &#39;&lt;command&gt;&#39; -e &#39;&lt;command&gt;&#39; &lt;filename&gt;<br><strong>e.g.</strong></pre><pre>livethedream$ sed -i -e &#39;/\s*#.*$/d&#39; -e &#39;/^ *$/d&#39; &lt;filename&gt;</pre><pre><strong>^</strong> <em>This chains the commands up to remove all # style comments and all blank/whitespace lines from your file or project, you can chain up more expressions and eventually come up with one-liners to clean your code up when required.</em></pre><p>You can create sed scripts by just putting one sed command per line into a file and calling it with the -f switch.</p><p><strong>File x.sed:</strong></p><pre>/\s*#.*$/d<br>/^ *$/d</pre><p><strong>Command:</strong></p><pre>livethedream$ sed -f x.sed &lt;filename&gt;</pre><p>Creating little sed scripts and keeping them handy to clean up code or even data-files (e.g. simple batch csv processing) can be a good use of this feature.</p><p>There is lots of commands for sed including the ability to read (/r) &amp; write (/w) to files, append (/a), insert (/i) and change (/c) lines and more right in the pattern itself. Explaining all of these much less utilised commands would make this article a small book. If you want to learn more about the capabilities of the sed version on your system, I recommend reading the man pages on your system using this command:</p><pre>livethedream$ man sed</pre><p>This will give you in-depth advice and commands for your exact system version be it GNU or BSD.</p><h3>Use — Replacing text in files</h3><p>I will now try to go through some basic use cases for aiding development using sed. As I mentioned, the most used command is the ‘substitute’. The -i switch means sed will edit the input file(s) in-place like in this example:</p><pre>livethedream$ sed -i s/&lt;search&gt;/&lt;replace&gt;/ &lt;filename&gt;<br><strong>e.g.</strong></pre><pre>livethedream$ cat file1.txt<br>abc<br>livethedream$ sed -i s/abc/cba/ file1.txt<br>livethedream$ cat file1.txt<br>cba<br>livethedream$ </pre><p>If you omit the -i switch, it will simply output the full input with any changes it makes, this makes it useful for using with pipes or any bash scripting scenarios. If we take the above example without -i, it works out like below — with file1.txt untouched.</p><pre>livethedream$ sed s/abc/cba/ file1.txt<br>cba<br>livethedream$ sed s/abc/cba/ file1.txt &gt; file2.txt<br>livethedream$<br><strong>^</strong> <em>This second command shows how you can easily take one file&#39;s sed output straight into a new file, keeping a copy of both states.</em></pre><h3>Use — Replacing text in all files in a folder/directory</h3><p>You can use the Bash shell * wildcard to unleash sed on the entire directory.</p><pre>livethedream$ sed -i /&lt;search&gt;/&lt;replace&gt;/ *<br><strong>e.g.</strong></pre><pre>livethedream$ sed -i s/abc/cba/ *</pre><h3>Use — Cleaning up code in your project or file</h3><p>You can go further with this sort of concept and start using the functionality of sed to clean up your code, remove unwanted function calls and such with commands like the ones below. Some of these examples utilise the ‘delete’ command specified of course by the letter d, working exactly like the substitute command but only taking one pattern to find and delete the offending matches.</p><pre>livethedream$ sed -i &#39;/^ *$/d&#39; &lt;filename&gt;</pre><pre><strong><em>^</em></strong><em> This removes all lines with just whitespace or that are blank.</em></pre><pre>livethedream$ sed -i s/&lt;function name&gt;\(\)\;// &lt;filename&gt;</pre><pre><strong><em>^</em></strong><em> This would remove all calls in a file or project to a certain function.</em></pre><pre>livethedream$ sed -i &#39;/\s*#.*$/d&#39; &lt;filename&gt;</pre><pre><strong><em>^</em></strong><em> This would remove all comments that use the # style from your file or project.</em></pre><pre>livethedream$ sed -i s/&lt;old variable/function/class name&gt;/&lt;new variable/function/class name&gt;/ &lt;filename&gt;</pre><pre><strong><em>^</em></strong><em> This last one is self explanatory really but it is very useful for when you need to change the name of something that gets referenced or called all over the place in a large project.</em></pre><p>You will notice the different styles of sed use that you can do, single quoting can be useful if your using certain characters in your command that will upset your preferred command line shell. The function call example above shows the other method of escaping your special characters using \, this is just another way to do the same thing.</p><h3>Teaming up with find</h3><p>Like in part one with Grep, you can pair sed up with find to really get recursive through a large project with some help from the xargs tool &amp; a pipe.</p><pre>livethedream$ find &lt;path&gt; -type f -print0 | xargs -0 sed -i &#39;s/&lt;find&gt;/&lt;replace&gt;/g&#39;<br><strong><em>^ print0</em></strong><em> (GNU find only) tells find to use the null character (\0) instead of whitespace as the output delimiter between files found. This is a safer option if your filenames contain blanks or other special characters. It is recommended to use the -print0 argument to find if you use -exec command or xargs (the -0 argument is needed in xargs.).</em></pre><p>Find called with -type f -print0 prints out a stream of all the filenames recursively in the specified path &amp; deeper. Xargs then calls sed with the required arguments of the filename, -i for in-place and the requested regular expression replacement. This can be used to quickly replace on a large scale.</p><pre>livethedream$ find &lt;path&gt; -type f -exec sed -i &#39;s/&lt;find&gt;/&lt;replace&gt;/g&#39; {} +<br><strong><em>^</em></strong><em> This is another option using find&#39;s -exec switch rather than the xargs solution - though the xargs solution is safer in some circumstances.</em></pre><p>You can also team up sed with anything else that outputs plaintext, so anything that outputs to std in your shell can be run through a sed command.</p><p>This concludes my brief introduction to using the great command line tool ‘sed’ for aiding development. There is lots of other great ways you can use sed to process any type of text file or even bash streams &amp; pipes . I have tried to show you the best switches and commands that get used with sed calls the most rather than going in-depth on every single piece of functionality it holds. It is a most powerful tool when leveraged correctly.</p><p>If you need a more adaptable advanced version of what sed does with even more functionality to really mangle your text definitely look into the command line tool <a href="https://en.wikipedia.org/wiki/AWK">AWK</a>.</p><p>If you like this article, please keep an eye out for part 3. If you have any feedback or questions please email me at <a href="/service/mailto:root@livingthedream.fun">root@livingthedream.fun</a>. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=228d462d3dda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Command Line Tools to Aid Development — Part 1 (Grep)]]></title>
            <link>https://live-the-dreams.medium.com/using-command-line-tools-to-aid-development-part-1-grep-bc9df65a2afe?source=rss-832969f3b93------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc9df65a2afe</guid>
            <category><![CDATA[grep]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[terminal]]></category>
            <dc:creator><![CDATA[Living The Dream]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 11:55:53 GMT</pubDate>
            <atom:updated>2019-03-18T11:55:53.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Vhh6TKif_M9PU80_nai7Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/Pyjp2zmxuLk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kevin Horvat</a> on <a href="https://unsplash.com/search/photos/linux-terminal?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Using Command Line Tools to Aid Development — Part 1 (Grep)</h3><p><em>This is a series of articles I have been writing for my personal blog, I want to start taking my writing to new levels — medium levels. I hope someone can gain from this something new &amp; I will be posting more parts to this series of articles soon. Have a great day!</em></p><p>In the world of development today everyone is looking to speed up the process while remaining efficient and not cutting corners, there is lots of different ways to achieve this but a lot of the time I find developers miss using some simple command line tools that can help certain things such as locating every use of a keyword (be it a variable name, function name, value etc) in an entire project and their locations to using linters to help you brush up to the strictest of standards.</p><p>Between the Bash shell, GNU/Linux and other command line tools you can save yourself time and pain while also boosting your overall skill set. This is going to be part one of a few parts where I will show not just the tools themselves but a couple of use cases that actually help during handling the development or maintenance of code/projects.</p><p>Introducing… grep, taken from Wikipedia the standard descriptive line would be ‘<em>grep</em> is a command-line utility for searching plain-text data sets for lines that match a regular expression’. As a base description that is pretty accurate but as time has gone on (the first version was released 1974 for the original Unix operating system) it has now got quite a few features and uses.</p><p>Before we get started, just incase someone is seriously new to the Bash terminal environment itself, this is my prompt which is where I type the commands:</p><pre>livethedream$ </pre><p>Your prompt will be different, please do not include it if you copy &amp; paste the grep commands, rather use anything after the $. Also if you see <strong>e.g. </strong>that is not output from grep, rather the beginning of some uses of the command being explained — you’d be surprised!</p><h3>Use — Searching a file for occurrences</h3><p>The plainest use of grep would be to purely search a file for an occurrence of a string. You can specify a regular expression or just a search string like so:</p><pre>livethedream$ grep &#39;&lt;search&gt;&#39; &lt;filename&gt;<br><strong>e.g.</strong></pre><pre>livethedream$ cat file.txt<br>test line<br>not a t-e-s-t line<br>livethedream$ grep test file.txt<br>test line<br>livethedream$ grep &#39;test&#39; file.txt<br>test line<br>livethedream$ grep ^test$ file.txt<br>test line<br>livethedream$</pre><p><strong>Note:</strong> The use of quote marks around the search term is optional but should be used if search contains any characters that would trigger the Bash shell (or your preferred platform) to interpret them as a split of the command/line or things like pipes etc.</p><h3>Use — Searching wider for occurrences</h3><p>You can use grep to search multiple files all the way up to multiple directories recursively file-by-file using the -R switch for recursive and multiple files, directories or the * wildcard which will match everything in the directory you are currently in.</p><pre>livethedream$ grep &lt;search&gt; &lt;multiple files&gt;<br><strong>e.g.</strong></pre><pre>livethedream$ grep test file.txt file2.txt file3.h file4.cpp <br>test line<br>livethedream$ grep -R &lt;search&gt; &lt;directory&gt;<br><br>livethedream$ grep -R test test_files/</pre><pre>livethedream$ grep -R test test_directory1/ test_directory2/</pre><pre>livethedream$ grep -R test * <br>- to search all files in current directory and all sub-directories, wildcard style.</pre><p>You can also mix file &amp; directories in the search radius.</p><pre>livethedream$ grep -R test.txt test_files/</pre><p>You will notice immediately when you give more than one file or any directories to be searched by grep that it will start reporting the file that the occurrence was found in at the start of each line so you can find which files contain what you were searching for.</p><pre>livethedream$ grep -R test test.txt some_files/<br>test.txt:testing<br>some_files/test.txt:test<br>livethedream$</pre><p>You can use grep with the wildcard solution in the root of your or other people’s code, libraries, projects etc to find where a function/class/variable is declared, defined, used etc this is really helpful in speeding up trying to find your way around code you either did a long time back or you are taking over maintaining from another developer or even modifying 3rd party code for your own devices.</p><h3>Use — Searching the pipe for occurrences</h3><p>Grep would not be what it is today without its use when put together with the traditional stream pipes that operating systems have been making use of since around the time of its first version. In a traditional Bash shell setup on a Unix/Linux system the pipe symbol | works by ‘piping’ the output of the command on the left hand side to the command on the right hand side and this can be chained over and over again for great effect.</p><p>Here is a typical example of using grep with a pipe to search the output of any command you can execute that has output:</p><pre>livethedream$ &lt;command&gt; | grep &lt;search&gt;<br><strong>e.g.</strong></pre><pre>livethedream$ ls<br>file1.txt   file2.txt   file3.txt   file4.txt   file5.txt   test.txt    test_files<br>livethedream$ ls | grep test<br>test.txt<br>test_files<br>livethedream$</pre><p>You can get really good results using grep in this way in regards to the development process by combining it with the output of tools like package managers, compilers, shell scripts, source control tools (git, hg, svn etc).</p><p>Another good use in the pipe instance is the -v switch which will reverse the usage to remove the occurrences rather than return them, so taking our above example lets try the same with -v.</p><pre>livethedream$ &lt;command&gt; | grep &lt;search&gt;<br><strong>e.g.</strong></pre><pre>livethedream$ ls<br>file1.txt   file2.txt   file3.txt   file4.txt   file5.txt   test.txt    test_files<br>livethedream$ ls | grep -v test<br>file1.txt<br>file2.txt<br>file3.txt<br>file4.txt<br>file5.txt<br>livethedream$</pre><p>You can see how this would be useful, you can even chain it instead of using a regular expression for quick removal of one or more separate searches like so:</p><pre>livethedream$ ls | grep -v test | grep -v file1 | grep -v file3<br>file2.txt<br>file4.txt<br>file5.txt<br>livethedream$</pre><p>You can also use this method with commands like cat, curl etc to parse your way through various types of data removing different searches quickly without mucking about with regex — a good example just for thought is using cat to view a csv file and using grep -v with multiple pipes to remove all lines that have a certain field value, only leaving the data left.</p><p>A quick example of this applying for searching development projects could be wanting to search for a function, but only search for it when it is called in a certain way or without a certain argument. I add the ( after the function name as an example of narrowing down making sure it is a function called.</p><pre>livethedream$ grep -R &#39;&lt;function name&gt;(&#39; * | grep -v &#39;(true)&#39;</pre><p>This call would search for all the calls (and the definition, but that isn’t relevant) of a function inside the entire project/codebase but removes all the times it is called with just one argument with a value of true as a boolean.</p><h3>Let’s do a use case on some real code</h3><p>Wordpress is a good example of a solid, well sized &amp; clean PHP open-source project, many of you will be familiar with it if you have a background in web development.</p><p>Say you wanted to locate everywhere where the_post(); a very popular Wordpress PHP function is called throughout your Wordpress installation.</p><pre>livethedream$ grep -R &#39;the_post(&#39; *<br>wp-admin/includes/class-wp-media-list-table.php:   the_post();<br>wp-admin/includes/dashboard.php:   $posts-&gt;the_post();<br>wp-content/themes/twentyseventeen/index.php:     the_post();<br>...<br>livethedream$</pre><p>As you can see, grep recursively searches through the entire project and starts spitting out not just every file the function was called in, but the line of code where it is called. Now what you might be about to ask is, how do you get the line number of these occurrences so you can go straight to destination? Grep has the -n switch for this giving us more essential help in locating code.</p><pre>livethedream$ grep -Rn &#39;the_post(&#39; *<br>wp-admin/includes/class-wp-media-list-table.php:627:   the_post();<br>wp-admin/includes/dashboard.php:865:   $posts-&gt;the_post();<br>wp-content/themes/twentyseventeen/index.php:39:     the_post();<br>...<br>livethedream$</pre><p>Now say you wanted to exclude everything that is a match inside the wp-content directory? We can use the pipe solution from earlier with the one above like so:</p><pre>livethedream$ grep -Rn &#39;the_post(&#39; * | grep -v &#39;wp-content&#39;<br>wp-admin/includes/class-wp-media-list-table.php:627:   the_post();<br>wp-admin/includes/dashboard.php:865:   $posts-&gt;the_post();<br>...<br>livethedream$</pre><h3>Introducing find (Bonus tool)</h3><p>What if we wanted to not locate code inside a file, but just locate a files path in the project by its name? Grep can help with this too but there is another little helpful tool to do this more efficiently called find which I will mention only briefly to help with this one case as people may assume Grep would be the tool for this and it can be used alongside it as well.</p><p>So say we want to find the path of the upgrade-functions.php file inside our Wordpress directory. We call find with the path . (current directory), -type f to switch it to file only mode and -name switch to search for the filename we want to find.</p><pre>livethedream$ find . -type f -name upgrade-functions.php<br>./wp-admin/upgrade-functions.php<br>livethedream$</pre><p>You see this works well and of course if you wanted to search for directories &amp; files with your specified name, you can omit the -type f switch.</p><p>I will just throw two more examples for some find cases out below, as I think with this utility &amp; grep there shouldn’t be anything in your projects you can’t locate!</p><pre>livethedream$ find . -type f -name &#39;*.php&#39; <strong>- locate every php file<br></strong>./wp-includes/class-oembed.php<br>./wp-includes/author-template.php<br>./wp-includes/admin-bar.php<br>...<br>livethedream$ find . -name *upgrade* <strong>- locate every file or directory with upgrade anywhere in the name</strong> <br>./wp-admin/ms-upgrade-network.php<br>./wp-admin/network/upgrade.php<br>./wp-admin/upgrade.php<br>...<br>livethedream$ find . -type d -name *upgrade* <strong>- locate only directories with upgrade anywhere in the name</strong><br>./wp-content/upgrade<br>livethedream$</pre><p>Make sure to single quote your -name string if you are searching for files by extension, as . counts as a special character.</p><p>This concludes the introduction to grep for use with searching through code specifically with a bit of find as a bonus. There is a whole host of other applications for grep and there is a couple of other really useful switches that can change the regular expression engine in use (if you use the regex with it) or how it searches. Be aware grep &amp; find have different versions depending on the operating system but mostly they are always the same in the way they act for most basic operations.</p><p>In part 2 of this series I will go even further with helping the development process using command line tools by introducing another key program that has a long history starting from the days of original Unix. Please feedback or clap if you want more or notice something I missed.</p><p>Live the code dream!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc9df65a2afe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>