<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" 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">
    <channel>
        <title>awwsmm.com</title>
        <link>http://awwsmm.com/</link>
        <description>Andrew Watson's blog about software development and related topics</description>
        <lastBuildDate>Wed, 30 Oct 2024 00:00:00 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>awesome</generator>
        <language>en</language>
        <image>
            <title>awwsmm.com</title>
            <url>https://www.awwsmm.com/images/profile.png</url>
            <link>http://awwsmm.com/</link>
        </image>
        <copyright>Feeds are for individual use in feed readers only and republishing this content is not permitted</copyright>
        <atom:link href="https://awwsmm.com/rss.xml" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[There is No Such Thing as a Unit Test]]></title>
            <link>https://awwsmm.com/blog/there-is-no-such-thing-as-a-unit-test</link>
            <guid isPermaLink="false">there-is-no-such-thing-as-a-unit-test</guid>
            <pubDate>Wed, 30 Oct 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Thinking differently about software testing paradigms]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><blockquote>
<p>"The terms 'unit test' and 'integration test' have always been rather murky, even by the slippery standards of most software terminology."<br>
-- <a href="https://martinfowler.com/articles/2021-test-shapes.html">Martin Fowler</a></p>
</blockquote>
<blockquote>
<p>"...there is no such thing as a Unit Test"<br>
-- <a href="https://blog.michael.gr/2022/10/incremental-integration-testing.html">Michael Belivanakis</a></p>
</blockquote>
<h2>What is a Unit Test?</h2>
<p>I typed the above question into a popular search engine, and the first three results I got back were as follows (emphasis mine)</p>
<blockquote>
<p>A unit test is a block of code that verifies the accuracy of a smaller, isolated block of application code, typically a function or method. -- <a href="https://aws.amazon.com/what-is/unit-testing/">aws.amazon.com</a></p>
</blockquote>
<blockquote>
<p>A unit test is a way of testing a unit - the smallest piece of code <strong>that can be logically isolated</strong> in a system. In most programming languages, that is a function, a subroutine, a method or property. -- <a href="https://smartbear.com/learn/automated-testing/what-is-unit-testing/">smartbear.com</a></p>
</blockquote>
<blockquote>
<p>Unit is defined as a single behaviour exhibited by the system under test (SUT), usually corresponding to a requirement. While it may imply that it is a function or a module (in procedural programming) or a method or a class (in object-oriented programming) <strong>it does not mean functions/methods, modules or classes always correspond to units</strong>. From the system-requirements perspective only the perimeter of the system is relevant, thus <strong>only entry points to externally-visible system behaviours define units</strong>. -- <a href="https://en.wikipedia.org/wiki/Unit_testing">Kent Beck via Wikipedia</a></p>
</blockquote>
<p>A problem I often see with modern software testing is that <a href="https://www.reddit.com/r/learnprogramming/comments/nwpzx9/how_can_unit_tests_be_useful_if_refactoring/">we lean toward the second definition too often</a>: a unit is "the smallest piece of code that can be logically isolated in a system". The word "can" is carrying a <em>lot</em> of weight in this sentence. We <em>can</em> logically isolate just about anything.</p>
<p>"Is a unit a file?"</p>
<p>-- "Definitely not", I can hear you say.</p>
<p>"Assuming an object-oriented program, how about a class?"</p>
<p>-- "Probably not", you say with slightly less conviction.</p>
<p>"How about a method?"</p>
<p>-- "Probably", with a bit more confidence, agreeing with the first two results above.</p>
<p>"What if that method is 300 lines of code?"</p>
<p>-- "Ooh, yeah, you should probably break that out into smaller methods."</p>
<p>Suppose we do this. Let's break our 300-line method into, say, 10 methods of 30 lines each, as <a href="https://www.reddit.com/r/learnprogramming/comments/toynah/when_i_was_in_undergrad_they_told_us_no_function/#:~:text=In%20general%2C%20the%20most%20common,should%20only%20do%20one%20thing.">some CS professors seem to teach their students that this is a good rule of thumb for function length</a>.</p>
<pre><code class="hljs language-scala"><span class="hljs-comment">// before</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">original</span></span>(x: <span class="hljs-type">String</span>, y: <span class="hljs-type">Int</span>): <span class="hljs-type">Boolean</span> = {

  <span class="hljs-comment">// ...</span>
  <span class="hljs-comment">// hundreds of lines of code</span>
  <span class="hljs-comment">// ...</span>

}
</code></pre>
<pre><code class="hljs language-scala"><span class="hljs-comment">// after</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">improved</span></span>(x: <span class="hljs-type">String</span>, y: <span class="hljs-type">Int</span>): <span class="hljs-type">Boolean</span> = {

  <span class="hljs-keyword">val</span> intermediateValueA = a(x)
  <span class="hljs-keyword">val</span> intermediateValueB = b(intermediateValueA, y)
  <span class="hljs-keyword">val</span> intermediateValueC = c(intermediateValueB)
  <span class="hljs-comment">// ...</span>
  <span class="hljs-keyword">val</span> intermediateValueH = h(intermediateValueG)
  <span class="hljs-keyword">val</span> intermediateValueI = i(intermediateValueH)
  
  j(intermediateValueI)

}

<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span></span>(x: <span class="hljs-type">String</span>): <span class="hljs-type">Long</span> = {
  <span class="hljs-comment">// ...</span>
}

<span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">b</span></span>(z: <span class="hljs-type">Long</span>, y: <span class="hljs-type">Int</span>): <span class="hljs-type">Double</span> = {
  <span class="hljs-comment">// ...</span>
}

<span class="hljs-comment">// eight more private functions...</span>
</code></pre>
<p>All of these methods could be <code>private</code> (or whatever your language's equivalent of that is). In that case, they can only be accessed by the class which contains them. They used to be all in one method anyway, so we can be sure nobody else is using this logic anywhere else.</p>
<p>But now we face another decision: should we write unit tests for all of these individual methods? For many of us, our gut reaction will be "yes". This could make refactoring more difficult in the future, though, because <a href="https://www.effective-software-testing.com/do-unit-tests-make-refactoring-harder">"the closer your tests are to the implementation the more sensitive they are to changes"</a>.</p>
<blockquote>
<p>Anecdotally, I've worked on codebases with hundreds of tests like this, all tightly coupled to the production implementation. Adding one field to a class meant updating a hundred or more tests which didn't care about this field at all, but needed the new field in order to compile. The test changes regularly took longer to implement than the production changes.</p>
</blockquote>
<p>Writing unit tests for these smaller methods might also require us to make them more <code>public</code> than they need to be; the world outside this class doesn't care about these individual methods, all it cares about is the one <code>improved</code> method which now ties them all together.</p>
<p>The real question is, are these functions "units" of code?</p>
<p>The answer is no.</p>
<p>As Kent Beck would say, these are not "entry points to externally-visible system behaviours".</p>
<p>The only externally-visible entry point in the refactored example above is the <code>improved</code> function, just as the <code>original</code> function was initially. But these pervasive ideas that...</p>
<ol>
<li>large functions should be broken up into smaller ones, and</li>
<li>a "unit test" is a "test of a single function"</li>
</ol>
<p>...combine to produce a result that is much worse than the sum of its parts: huge suites of tests tightly-coupled to unnecessarily-public production code that take too long to write and are difficult to maintain.</p>
<p>Outcomes like this lead many developers to believe things like...</p>
<blockquote>
<p>"Most Unit Testing is Waste"<br>
-- <a href="https://wikileaks.org/ciav7p1/cms/files/Why-Most-Unit-Testing-is-Waste.pdf">James O. Coplien</a></p>
</blockquote>
<h2>Kinds of Tests</h2>
<p>Rather than thinking of tests along the traditional <a href="https://qase.io/blog/test-pyramid/">unit / integration / end-to-end spectrum</a>, I think it's helpful to think along a few other dimensions</p>
<ol>
<li>is this test <em>fast</em> or <em>slow</em>?</li>
<li>is this a <em>black-box</em> test or a <em>white-box</em> test?</li>
<li>is this test <em>informed by</em> development or does <em>it inform</em> development?</li>
</ol>
<h3>Fast and Slow Tests</h3>
<p>Let me start by asserting that "fast" is not synonymous with "good", and "slow" is not synonymous with "bad" in this context.</p>
<p>Fast tests are tests that run in a few seconds, milliseconds, microseconds, or less. Fast tests, therefore, must be entirely in-memory. They <a href="https://gist.github.com/jboner/2841832">do no disk IO and they make no network calls</a>. They can be run every single time a code change is made without being a roadblock to development speed, and should therefore be run as part of the developer's <a href="https://www.awwsmm.com/blog/drop-everything-and-review">inner loop</a>. Every time you compile, you can run these tests.</p>
<p>Slow tests take several seconds, minutes, or hours to run. The dividing line between fast and slow tests is somewhere around 2-5 seconds. Slow tests may require reading large input files from disk, doing lots of computation, or communicating across the network. That is: they are <a href="https://stackoverflow.com/q/868568/2925434">IO, CPU, or network <em>bound</em></a>. <a href="https://testsigma.com/blog/api-contract-testing/">Contract tests</a> (which often spin up Docker containers) and performance tests (which may run gigabytes of data or thousands of requests through the system) are examples of slow tests. These tests should be run less regularly, as they can impact development speed: before each commit to <code>main</code> / <code>master</code> is probably fine for tests shorter than a few minutes, daily or weekly might be a good cadence for tests much longer than that.</p>
<h3>Black-Box and White-Box Tests</h3>
<p>Black-box tests make no assumptions about the internals of the thing they are testing. They provide inputs and assert on observable outputs, and that's it. The observable output is usually a return value from a method, but a black-box test might instead assert that a side effect has occurred, like that a log line has been written, or that a metric has been recorded, or that some state has been mutated.</p>
<p>White-box tests specifically test the internals of the thing they are testing. They are <a href="https://stackoverflow.com/a/25199156/2925434"><em>introspective</em></a>. Tests which have assertions like "when 'x' happens, function a() should call function b()" are white-box tests. They are explicitly testing <em>how</em> something should happen (<em>how</em> some code is implemented), rather than testing only that it <em>has</em> happened. Tests which rely heavily on mocking frameworks are often white-box tests, asserting that <a href="https://sachithradangalla.medium.com/mockito-verify-how-to-test-method-invocations-8cf15be9bc19">such-and-such a method has (or hasn't) been called</a> in response to some inputs.</p>
<p>If you don't care about <em>how</em> something is implemented -- just that that it does what it's supposed to do -- you should write a black-box test. This is usually the case, so opt for black-box tests as a default.</p>
<h3>Development-Informed Tests and Development-Informing Tests</h3>
<p>Development-informed tests are written <em>reactively</em>, in that the production code is written first, and the tests are written afterward. Development-informed tests codify the behaviour of the system as-is. Traditional "unit tests" are almost exclusively development-informed tests.</p>
<p>Development-informing tests are written <em>proactively</em>, in that a test is written first, and the production code is written after. <a href="https://en.wikipedia.org/wiki/Test-driven_development">Test-Driven Development (TDD)</a> is a software development methodology which encourages writing <em>only</em> development-informing tests, ensuring that 100% of the system's behaviour is always codified in tests.</p>
<p>Development-informing tests can also provide confidence that some tricky piece of logic has been implemented correctly. For example, you might write a <a href="https://en.wikipedia.org/wiki/Regular_expression">regex</a> to parse U.S. phone numbers, and -- at the same time -- add a handful of tests to ensure that you catch things like</p>
<ul>
<li>area codes surrounded by parentheses</li>
<li>spaces vs. no spaces vs. hyphens</li>
<li>the presence or absence of a <code>+1</code> country code</li>
</ul>
<p>It can be hard to be sure -- just by staring at the regular expression -- that it catches all of these cases. Usually it's more convincing to just write a handful of simple tests to convince yourself that the most common edge cases are being handled correctly.</p>
<p>I always write bug fix tests in a development-informing way, as well. First, I write a test which <em>should</em> pass, but which I expect to fail due to the presence of a bug. Then, I fix the bug in the production code, ensuring that the test now passes. This process shows that -- had the test existed originally -- it would have caught the bug. This gives confidence that the bug should not reappear in the future.</p>
<h2>"Most Unit Testing is Waste"</h2>
<p>The three ways of looking at tests outlined above can provide insight into why developers like <a href="https://wikileaks.org/ciav7p1/cms/files/Why-Most-Unit-Testing-is-Waste.pdf">James O. Coplien</a> believe that most unit testing is a waste of time.</p>
<h3>Most Unit Tests are Development-Informed</h3>
<p>In my experience, TDD is not practiced by <a href="https://www.reddit.com/r/ExperiencedDevs/comments/1g1xdqu/do_you_guys_use_tdd/"><em>most</em></a> developers.</p>
<p>Most tests, therefore, are development-informed. A developer writes some production code and then writes a test, usually to ensure that some <a href="https://www.atlassian.com/continuous-delivery/software-testing/code-coverage#:~:text=With%20that%20being%20said%20it,fairly%20low%20percentage%20of%20coverage.">code coverage minimum</a> is reached.</p>
<p>These tests are not written to catch bugs, and they are not written to help a developer think through some difficult implementation, and so their value is not immediately apparent.</p>
<h3>Most Unit Tests do not test "Externally-Visible System Behaviours"</h3>
<p>As mentioned earlier, the twin practices of (1) breaking large functions up into smaller ones and (2) writing tests for each <em>function</em> rather than for each <em>externally-visible system behaviour</em> leads to a proliferation of tests tightly-coupled to the production implementation. These tests are, by their nature, fragile. They must be updated whenever the smallest implementation detail is changed, even if the externally-visible system behaviour is identical.</p>
<blockquote>
<p>This often happens when using mocking frameworks, since every method called on <a href="https://www.digitalocean.com/community/tutorials/mockito-mock-examples">a mocked object</a> must be declared, with its return value specified.</p>
</blockquote>
<p>In the worst-case scenario, developers will sometimes copy-and-paste the production implementation directly into the test, asserting that the "expected" result from the test implementation equals the "actual" result from the production code. This kind of white-box test unquestionably adds no value, even if it does increase "code coverage".</p>
<h2>A New Test Pyramid</h2>
<p>The traditional <a href="https://qase.io/blog/test-pyramid/">test pyramid</a> aims to emphasise to developers that they should be mostly writing "unit tests", with fewer "integration tests" and only a handful of "end-to-end tests". Although different formulations of the pyramid may use different terms for the latter two levels, almost all agree that the base of the pyramid should be composed of "unit tests". <a href="https://testing.googleblog.com/2015/04/just-say-no-to-more-end-to-end-tests.html">Google recommends</a> a 70% / 20% / 10% split of unit / integration / end-to-end tests.</p>
<p>The idea is that you should cover most of the code's logic in small, fast tests which can be run over and over during the <a href="https://www.awwsmm.com/blog/drop-everything-and-review">inner loop of development</a>. Your integration tests should cover interactions between units; and your end-to-end tests should validate that an end user's actions result in some expected overall outcome.</p>
<p>That advice is fine, provided all developers agree what constitutes a "unit test" or an "integration test". Clearly this is not the case. (See the search engine results at the top of this blog post.) However, we can use the objective criteria above (fast vs. slow, black-box vs. white-box, development-informed vs. development-informing) to construct a New Test Pyramid.</p>
<p><img src="/blog/there-is-no-such-thing-as-a-unit-test/pyramid.png" alt="A New Test Pyramid"></p>
<h3>The Base</h3>
<p>Opt for black-box tests wherever possible. Where external dependencies are required, prefer <a href="https://stackoverflow.com/q/346372/2925434">fake</a> implementations <a href="https://testing.googleblog.com/2024/02/increase-test-fidelity-by-avoiding-mocks.html">rather than mocks</a> (and add corresponding contract tests to ensure that external dependency behaves as you think it does). This keeps the entire test in-memory, making it fast enough to run before each commit to <code>main</code> / <code>master</code>. You will find that most of your tests are these fast, black-box tests.</p>
<p>Note that this is <em>not</em> synonymous with "unit test". As discussed above, traditional "unit tests" are usually fast, but are sometimes white-box tests, and are often development-informed.</p>
<h3>The Middle</h3>
<p>Prefer development-informing tests over development-informed tests (prefer a TDD style of development). Development-informed tests are often written <a href="https://www.merriam-webster.com/dictionary/rote">by rote</a> and offer little value.</p>
<p>Prefer slow black-box tests over fast white-box tests. The former are easier to maintain as they are less tightly-coupled to the production implementation.</p>
<p>Traditional "integration tests" and "end-to-end" tests both fall into the "slow, black-box tests" category.</p>
<h3>The Top</h3>
<p>Write as few white-box tests as possible. That is, do as little code introspection as possible. Only test observable outputs.</p>
<p>Write development-informed tests only when necessary. If the production implementation works, it works. If it doesn't, you will find a bug, write a development-informing test, and fix the bug. This process is described above.</p>
<h2>Conclusion</h2>
<p>The traditional unit / integration / end-to-end categorization of tests is fuzzy at best. Differing interpretations of what constitutes a "unit test", combined with well-intentioned but misapplied advice on keeping code readable by reducing the number of lines per function, class, etc. has led to a proliferation of hard-to-maintain, low-value test suites that negatively impact developer productivity.</p>
<p>Categorizing tests objectively, using the three criteria described above, can lead to more maintainable tests which provide more value.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[Code as Art]]></title>
            <link>https://awwsmm.com/blog/code-as-art</link>
            <guid isPermaLink="false">code-as-art</guid>
            <pubDate>Sat, 17 Aug 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Computer programming as an art form in and of itself]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><h2>Digital Art</h2>
<p>In almost all circumstances, code is a means to an end.</p>
<p>The phrase "computer programming" itself describes the activity of <em>programming</em> a <em>computer</em> to accomplish a particular task. Often, that task is logical. Most computer programs do something "useful", whether that's calculating the best route from your home to work, balancing a budget, or running your <a href="https://www.cbsnews.com/news/teen-goes-viral-for-tweeting-from-lg-smart-fridge-after-mom-confiscates-all-electronics/">smart fridge's Twitter client</a>.</p>
<p>But many programs are written solely to produce something of aesthetic value.</p>
<p>Recently, Generative AI applications like <a href="https://www.midjourney.com/showcase">Midjourney</a>, which can produce visual art from text prompts, have seen a lot of press. But consider also <a href="https://www.dwitter.net/top/all">dwitter.net</a>, where JavaScript programs of 140 characters or fewer create moving 3D landscapes, gyrating fractals, and even <a href="https://www.dwitter.net/d/135">self-playing games of Pong</a>. And also programmers like <a href="https://codepen.io/Wujek_Greg/pen/LmrweG">Grzegorz Witczak</a>, <a href="https://codepen.io/ivorjetski/pen/xxGYWQG">Ben Evans</a>, and <a href="https://diana-adrianne.com/">Diana A. Smith</a> who create photorealistic works of art using only <a href="https://en.wikipedia.org/wiki/CSS">CSS</a>, a language otherwise used mainly to style fonts, borders, and backgrounds on web pages.</p>
<p><a href="https://en.wikipedia.org/wiki/Digital_art">Digital art</a> is not a new phenomenon. Nearly as long as computers have existed, programmers have been using them to express themselves aesthetically.</p>
<blockquote>
<p>Traditional artists have been inspired by digital art, as well. Consider Dalí's <a href="https://www.salvador-dali.org/en/artwork/catalogue-raisonne-paintings/obra/871/painting-of-gala-looking-at-the-mediterranean-sea-which-from-a-distance-of-20-meters-is-transformed-into-a-portrait-of-abraham-lincoln-homage-to-rothko"><em>Painting of Gala looking at the Mediterranean sea which from a distance of 20 meters is transformed into a portrait of Abraham Lincoln (Homage to Rothko)</em></a>, produced in 1976, which appears to show a pixelated image of Abraham Lincoln when viewed from a distance.</p>
</blockquote>
<p>For most digital artists, code is a <em>medium</em>, like marble for a sculptor, or a canvas for a painter. Code is the material through which the art is <em>expressed</em>. Though it takes time and skill to produce, a canvas itself is not usually seen as art itself. But <a href="https://www.npr.org/2021/09/29/1041492941/jens-haaning-kunsten-take-the-money-and-run-art-denmark-blank">could it be</a>?</p>
<h2>Readability</h2>
<p>Developers often talk about writing <a href="https://en.wiktionary.org/wiki/clean_code">"clean"</a> or <a href="https://www.quora.com/What-do-programmers-mean-by-elegant-code">"elegant" code</a>. Most programming languages are <a href="https://en.wikipedia.org/wiki/General-purpose_programming_language">"general-purpose"</a>, meaning they can be used to accomplish a variety of tasks. Accordingly, there are often many different ways to accomplish the <em>same</em> task, using the same programming language.</p>
<p>Robert C. Martin's <a href="https://www.oreilly.com/library/view/clean-code-a/9780136083238/"><em>Clean Code: A Handbook of Agile Software Craftsmanship</em></a> gives many examples of "unclean" code, with tips and rules of thumb for rewriting the code in a "clean" way.</p>
<p>In the overwhelming majority of cases, the most important aspect of code is its functionality -- usually to perform some computational task. A <em>secondary</em> aspect of the code is its <em>readability</em>, closely related to the "cleanliness", "elegance", or "aesthetics" of the code.</p>
<p>As a quick example, consider this 3x3 matrix</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">val</span> identity = <span class="hljs-type">Array</span>(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>)
</code></pre>
<p>Which elements are on the diagonal of this matrix?</p>
<p>It's much more <em>readable</em> if we <a href="https://scalameta.org/scalafmt/docs/configuration.html#-format-off">manually format it</a> as follows</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">val</span> identity = <span class="hljs-type">Array</span>(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>,
                     <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>,
                     <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>)
</code></pre>
<p>These two arrays are functionally identical. But <em>aesthetically</em>, the source code used to construct the latter array is more "readable" than the former. Functionality is paramount, but aesthetics are a close second.</p>
<p>But what if a program (or an entire programming language) were designed <em>primarily</em> for its aesthetic qualities?</p>
<h2>Unreadability</h2>
<p>Formatting code for readability -- or to follow established patterns and idioms -- is the norm. But some programmers do the opposite (intentionally or otherwise).</p>
<p>Every year, the International Obfuscated C Code Contest (<a href="https://www.ioccc.org/">IOCCC</a>) accepts submissions of C code which accomplish some task, but do it in an unusual, hard-to-decipher way. These programs are functional, but are purposely formatted so as to be as <em>unreadable</em> as possible (they are <em>obfuscated</em>).</p>
<p>Some programming languages have been designed specifically to accomplish as much as possible in as few characters as possible. <a href="https://en.wikipedia.org/wiki/APL_(programming_language)#Game_of_Life">APL</a> is a "serious" (non-"esoteric") and very terse programming language which programmers may be familiar with, but many <a href="https://en.wikipedia.org/wiki/Code_golf">code golf</a> languages have been created specifically to minimize source code size in a similar way.</p>
<p>And some programmers choose to format their code so that their entire ray-tracing C++ program can <a href="https://mzucker.github.io/2016/08/03/miniray.html">fit on the back of a business card</a>, or so <a href="https://github.com/mame/quine-relay/blob/master/QR.rb">the source code</a> of their <a href="https://en.wikipedia.org/wiki/Quine_(computing)#Ouroboros_programs">ouroborous quine</a> written in Ruby looks like a dragon (see the header image of this blog post), or so that they <a href="https://code-poetry.com/">look like and can be read as poems</a>. All of these examples use "serious" programming languages in an "unserious" way.</p>
<h2>Esoteric Languages</h2>
<p>There are also many programming languages where the <a href="https://www.awwsmm.com/blog/20-intriguing-unusual-and-goofy-programming-languages#aesthetics">aesthetics of the source code</a> is more important than what is actually written in that code. As most programming languages are written using ASCII or Unicode character sets, <a href="https://web.archive.org/web/20240205064805/https://blue.sky.or.jp/grass/">some of these</a> look like <a href="https://en.wikipedia.org/wiki/ASCII_art">ASCII art</a>...</p>
<pre><code>　　　　_, ._
　　（　・ω・）　んも〜
　　○=｛=｝〇,
　 　|:::::::::＼, ', ´
､､､､し ､､､((（.＠）ｗｖｗｗＷＷｗｖｗｗＷｗｗｖｗｗｗｗＷＷＷｗｗＷｗ
ｗＷＷＷＷＷＷｗｗｗｗＷｗｗｖｗＷＷｗＷｗｗｖｗＷＷＷ
</code></pre>
<p>...though most just look like <a href="https://esolangs.org/wiki/Labyrinth">jumbled messes of characters</a></p>
<pre><code> 72_1_108::_3+:}
    0          _ """
     11_{78_23_" " "
     4         4 ".{@
     _         " {
     1           }"
     08_100_33"""""
</code></pre>
<p>Some esoteric programming languages are <a href="https://esolangs.org/wiki/Category:Non-textual">non-textual</a>. The source code of these programs can be visual, as with <a href="https://www.dangermouse.net/esoteric/piet/samples.html">Piet</a></p>
<p><img src="/blog/code-as-art/piet.gif" alt="&#x22;Hello World&#x22; in the Piet programming language"></p>
<p>or <a href="https://esolangs.org/wiki/Nice">Nice</a> (which does not yet have a working interpreter)</p>
<p><img src="/blog/code-as-art/nice.png" alt="&#x22;Hello World&#x22; in the Nice programming language"></p>
<p>Other languages are auditory, meaning programs are encoded as sound. Usually, these programs can also be written <a href="https://esolangs.org/wiki/Sound">as individual notes</a>, or as <a href="https://esolangs.org/wiki/Hello_world_program_in_esoteric_languages_(D-G)#Fugue">sheet music</a></p>
<p><img src="/blog/code-as-art/fugue.png" alt="&#x22;Hello World&#x22; in the Fugue programming language"></p>
<figure style="display:block;text-align:center">
  <figcaption>Listen to the above program</figcaption>
  <audio controls src="/blog/code-as-art/fugue-hello-world.mp3"></audio>
</figure>
<p>In many cases, the simplest implementation of a program in these languages is not the most aesthetically pleasing. Programmers will opt for beautiful programs over efficient ones.</p>
<p>For example, the following Piet program gets a number as input from the user, squares it, and prints the result</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/1clwo2qss6zurm2kisdw.png" alt="A sample Piet program"></p>
<p>...but so does this one</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/i77oznhfqnyu147wxesz.png" alt="A simple Piet program"></p>
<h2>Code as Art</h2>
<blockquote>
<p>"There is no generally agreed definition of what constitutes art" [<a href="https://en.wikipedia.org/wiki/Art">Wikipedia</a>]</p>
</blockquote>
<p>Even in languages which aren't specifically designed to have "beautiful" source code, some programmers opt to format their code in ways which trade efficiency, practicality, or readability for aesthetic appeal.</p>
<p>There is no single, correct solution to a problem which can be solved by a program. Different programs can accomplish the same task in different ways. Weighing tradeoffs and choosing one solution over another is part of the art of computer programming.</p>
<p>The human desire to be creative and express one's individuality does not end where a keyboard begins. Hundreds of esoteric programming languages can attest to that.</p>
<p>Whether textual, visual, or auditory, code can be used as a medium to create art, but it can also <em>be</em> art itself.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[Solving for the Minimum Number of Unique Values in a Set]]></title>
            <link>https://awwsmm.com/blog/solving-for-the-minimum-number-of-unique-values-in-a-set</link>
            <guid isPermaLink="false">solving-for-the-minimum-number-of-unique-values-in-a-set</guid>
            <pubDate>Mon, 29 Apr 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Given only inequality relationships between members of the set]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><h2>Sayonara Scala Steward</h2>
<p>One of my ongoing projects at work is developing and maintaining an in-house dependency updating solution for our code.</p>
<p>We used to use <a href="https://github.com/scala-steward-org/scala-steward">Scala Steward</a> to keep our Scala projects up-to-date, but found that it <a href="https://medium.com/permutive/scala-steward-without-the-noise-da7424f3c315">created a lot of noise</a> -- failed pipelines, merge conflicts, and new versions of software being released where the only change was a patch version bump to a dependency.</p>
<p>We wanted a cleaner solution</p>
<ul>
<li>one update PR per week per repo, containing all of the dependency updates</li>
<li>PRs with failed pipelines would be assigned to a "repo owner" who could resolve them during the week</li>
<li>and next week, if that PR was still open, it would be closed in favour of a new one</li>
</ul>
<p>The last point ensures that at most one dependency update PR is open at any given time for any project. This seriously reduces the mental overhead on the developer (usually, the team lead) tasked with handling these weekly update PRs.</p>
<p>This project is implemented in two parts.</p>
<p>First, there's the <a href="https://gitlab.com/improving-andrew/sbt-dependency-updater"><code>sbt-dependency-updater</code></a>, which adds an <code>updateDependencies</code> task to any <a href="https://www.scala-sbt.org/"><code>sbt</code></a>-managed Scala project (as all of ours are). This task makes it easy to update all of the dependencies for a specific repo. (Note that the way in which these dependencies are updated is pretty primitive and could use some refinement.)</p>
<p>Second, there's a (privately-hosted) <code>dependency-updater</code> repo which uses GitLab pipelines and the GitLab API to clone a project, run <code>updateDependencies</code> in that project, and -- if there is a nonzero number of updates -- create a branch and MR against <code>master</code> / <code>main</code>, assigning the team lead to the MR.</p>
<p>It's all been working very smoothly for the past few months. Noise (both cognitive and pipeline) has decreased significantly, and dependencies are as up-to-date as they have always been.</p>
<p>But this blog post is not about that dependency updating software; it's about how we grouped our dozens of repos into "Tiers", based on dependencies, to ensure that everything is always as up-to-date as possible.</p>
<h2>Tiers</h2>
<p>A repository of code has some list of dependencies (upstream libraries which it uses to do its job).</p>
<p>Suppose you have some <code>infrastructure</code> library which is depended on by most projects, and a <code>utilities</code> library which depends on <code>infrastructure</code>, and that most projects also depend on <code>utilities</code>.</p>
<p>In order to ensure that some project <code>a</code> has the latest version of <code>utilities</code> and the latest version of <code>infrastructure</code>, ideally with no transitive version conflicts, we want to do something like the following</p>
<ol>
<li>update <code>infrastructure</code>'s dependencies</li>
<li>update <code>utilities</code>'s dependencies, which include <code>infrastructure</code></li>
<li>update <code>a</code>'s dependencies, which include <code>utilities</code> and <code>infrastructure</code></li>
</ol>
<p>A natural step-by-step process has emerged. Here we introduce some terminology and say that projects which can be updated at the same time belong to the same "tier". For instance, if we have another project <code>b</code> which also depends on <code>utilities</code> and <code>infrastructure</code>, then <code>a</code> and <code>b</code> can be updated simultaneously (in the same CI pipeline) without any problems. But if <code>b</code> depends on <code>a</code>, then updating <code>b</code>'s dependencies should happen <em>after</em> updating <code>a</code>'s dependencies. <code>b</code> gets bumped into a lower tier.</p>
<p>This begs the question: <em>what is the minimum required number of tiers for some set of projects with dependencies on each other</em>? In other words, by analyzing their dependencies, how can we efficiently group a set of projects into tiers such that updates to higher tiers efficiently "flow" into lower tiers during the course of the week's dependency updates?</p>
<h2>Problem Statement</h2>
<p>Given a set of <code>N</code> values representing projects: <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, and <code>e</code>, let inequality relationships between the values indicate dependencies between projects. For example, <code>a &#x3C; b</code> indicates that <code>a</code> depends on <code>b</code>.</p>
<p>What is the minimum number of unique values that can be assigned to <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, and <code>e</code>, given some set of <code>M</code> unique inequality relationships?</p>
<p>"Unique equality relationships" means <code>a &#x3C; b</code> and <code>b > a</code> count as only a single relationship, because they are just two different ways to express the same information.</p>
<h2>Discussion</h2>
<p>I'm not planning on <em>proving</em> this in the mathematical sense, but I think we can come up with an intuitive solution by thinking through this problem logically.</p>
<p>Let's start with <code>M = 0</code>. This is the case where there is <em>no</em> inequality information. In this case, there is no reason we cannot assume <code>a = b = c = d = e</code>, and put all dependencies in the same tier. The minimum number of unique values in this case is <code>1</code>, when there is only a single tier. So in the <code>M = 0</code> case, we have no inequality information, and <code>1</code> tier is sufficient when <code>N = 5</code> and <code>M = 0</code>.</p>
<p><code>1</code> is the minimum number of unique values when <code>N = 5</code> and <code>M = 0</code>.</p>
<blockquote>
<p>Note that <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, and <code>e</code> <em>could</em> also have five unique values. This is always possible if we assume that there <em>exists</em> some additional information which we are just not currently aware of. But the problem we are trying to solve is the <em>minimum</em> number of unique values <em>required</em> to satisfy the known information.</p>
</blockquote>
<p>In the <code>M = 1</code> case we have a single unique inequality, for example <code>a &#x3C; b</code>. Here, we must have at least two unique values, since <code>a</code> and <code>b</code> are explicitly not equal; <code>b</code> is in tier <code>1</code> and <code>a</code> is in tier <code>2</code>. However, <code>c</code>, <code>d</code>, and <code>e</code> can fall into either tier without contradicting any known inequality information, so <code>2</code> is the minimum number of unique values when <code>N = 5</code> and <code>M = 1</code>.</p>
<p><code>M = 2</code> is where things start to get interesting, because there are two kinds of scenarios here.</p>
<p>First, suppose our two known inequalities are <code>a &#x3C; b</code> and <code>b &#x3C; c</code>. This requires <code>a</code>, <code>b</code>, and <code>c</code> to have three unique values, and so we require three tiers. But if our two known inequalities are <code>a &#x3C; b</code> and <code>a &#x3C; c</code>, then it's possible that <code>b = c</code>, and only two tiers are required. In fact, we could have up to four inequalities and still only require two tiers, if <code>a &#x3C; b</code>, <code>a &#x3C; c</code>, <code>a &#x3C; d</code>, and <code>a &#x3C; e</code>. In this case, <code>b = c = d = e</code>, <code>a</code> is in tier 2, and all other projects are in tier 1.</p>
<p>So <code>2</code> is the minimum number of unique values when <code>N = 5</code> and <code>0 &#x3C; M &#x3C;= 4</code>.</p>
<p>But when <code>M = 5</code> something changes. If our initial four inequalities are <code>a &#x3C; b</code>, <code>a &#x3C; c</code>, <code>a &#x3C; d</code>, and <code>a &#x3C; e</code>, and we add a fifth unique inequality, we must split tier <code>1</code> into two tiers. For example, if <code>b &#x3C; c</code>, then <code>a</code>, <code>b</code>, and <code>c</code> must exist in different tiers, and the minimum required number of tiers is <code>3</code>.</p>
<p>But like the <code>1 &#x3C; M &#x3C;= 4</code> case, we can continue to add inequalities for a while with only three tiers. If <code>b &#x3C; d</code> and <code>b &#x3C; e</code>, then it's possible that <code>c = d = e</code>, <code>a &#x3C; b</code>, and <code>b &#x3C; c</code>, and all of our previous inequalities still hold (<code>a &#x3C; b</code>, <code>a &#x3C; c</code>, <code>a &#x3C; d</code>, <code>a &#x3C; e</code>, <code>b &#x3C; c</code>, <code>b &#x3C; d</code>, and <code>b &#x3C; e</code>).</p>
<p>So <code>3</code> is the minimum number of unique values when <code>N = 5</code> and <code>4 &#x3C; M &#x3C;= 7</code>.</p>
<p>You may be starting to see where this is going. If we add another inequality, say <code>c &#x3C; d</code>, we require a fourth tier. But four tiers is also enough for <em>another</em> inequality, <code>c &#x3C; e</code>.</p>
<p><code>4</code> is the minimum number of unique values when <code>N = 5</code> and <code>7 &#x3C; M &#x3C;= 9</code>.</p>
<p>Finally, when <code>N = 5</code>, we can have at most <code>M = 10</code> unique inequalities. For example: <code>a &#x3C; b</code>, <code>a &#x3C; c</code>, <code>a &#x3C; d</code>, <code>a &#x3C; e</code>, <code>b &#x3C; c</code>, <code>b &#x3C; d</code>, <code>b &#x3C; e</code>, <code>c &#x3C; d</code>, <code>c &#x3C; e</code>, and <code>d &#x3C; e</code>. This uniquely orders all projects <code>a &#x3C; b &#x3C; c &#x3C; d &#x3C; e</code> and requires the maximum number of <code>5</code> tiers.</p>
<p><code>5</code> is the minimum number of unique values when <code>N = 5</code> and <code>M = 10</code>.</p>
<p>Let's recap. If <code>k</code> is the minimum number of unique values required, then, when <code>N = 5</code></p>
<ul>
<li>when <code>M = 0</code>, <code>k = 1</code></li>
<li>when <code>0 &#x3C; M &#x3C;= 4</code>, <code>k = 2</code></li>
<li>when <code>4 &#x3C; M &#x3C;= 7</code>, <code>k = 3</code></li>
<li>when <code>7 &#x3C; M &#x3C;= 9</code>, <code>k = 4</code>, and</li>
<li>when <code>M = 10</code>, <code>k = 5</code></li>
</ul>
<p>Writing this another way</p>
<ul>
<li>when <code>M = 0</code>, <code>k = 1</code>, else</li>
<li>when <code>M &#x3C;= 4</code>, <code>k = 2</code>, else</li>
<li>when <code>M &#x3C;= 4 + 3</code>, <code>k = 3</code>, else</li>
<li>when <code>M &#x3C;= 4 + 3 + 2</code>, <code>k = 4</code>, and</li>
<li>when <code>M = 4 + 3 + 2 + 1</code>, <code>k = 5</code></li>
</ul>
<p>The <a href="https://en.wikipedia.org/wiki/Triangular_number">triangular numbers</a> have emerged. If <code>T(N)</code> is the <code>N</code>th triangular number, then</p>
<ul>
<li><code>T(0) = 0</code></li>
<li><code>T(1) = 1</code></li>
<li><code>T(2) = 3</code></li>
<li><code>T(3) = 6</code></li>
<li><code>T(4) = 10</code></li>
</ul>
<p>So we can re-express the above as</p>
<ul>
<li>when <code>M = 0</code>, <code>k = 1</code>, else</li>
<li>when <code>M &#x3C;= T(4) - T(3)</code>, <code>k = 2</code>, else</li>
<li>when <code>M &#x3C;= T(4) - T(2)</code>, <code>k = 3</code>, else</li>
<li>when <code>M &#x3C;= T(4) - T(1)</code>, <code>k = 4</code>, and</li>
<li>when <code>M = T(4)</code>, <code>k = 5</code></li>
</ul>
<p>Since <code>M</code> is bounded by the range <code>[0, T(4)]</code> when <code>N = N</code>, this covers all possible values of <code>M</code> and <code>k</code>.</p>
<p>We can postulate that, for any set of <code>N</code> values, described only by <code>M</code> unique inequalities between values, the set must be composed of at least <code>k</code> unique values, where</p>
<ul>
<li><code>M</code> is bounded by the range <code>[0, T(N-1)]</code></li>
<li>when <code>M = 0</code>, <code>k = 1</code></li>
<li>when <code>M = T(N-1)</code>, <code>k = N</code>, and</li>
<li><code>T(N-1) - T(k) &#x3C; M &#x3C;= T(N-1) - T(k-1)</code></li>
</ul>
<h2>Future Work</h2>
<h3>Optimal Number of Tiers</h3>
<p>The above reasoning was enough to convince me that this is procedure gives the correct <em>minimum</em> number of tiers required for staggered, grouped dependency updates. But the next step is more difficult -- actually determining what those tiers should be.</p>
<p>It's easy to see that when <code>a &#x3C; b</code> and <code>b &#x3C; c</code>, we can construct three tiers...</p>
<ul>
<li>tier 1: <code>c</code>, <code>d</code>, and <code>e</code> (these receive dependency updates first)</li>
<li>tier 2: <code>b</code> (then this project receives dependency updates)</li>
<li>tier 3: <code>a</code> (and finally, this one)</li>
</ul>
<p>...but that <code>d</code> and <code>e</code> can be put into any tier.</p>
<p>However, it's much harder to reason about what the tiers should be, and where projects should be placed on them, when you have dozens of projects with dozens of dependencies. We know the <em>minimum</em> number of tiers from the above analysis, but we've also seen that this minimum is exceeded when we have dependency chains like <code>a &#x3C; b &#x3C; c</code>. Does the longest dependency chain determine the "optimal" number of tiers? Can we prove this? Can we turn this process into an algorithm?</p>
<h3>Circular Dependencies</h3>
<p>Another possible extension to this problem is the idea of <em>circular dependencies</em>. In the real world, it's possible (though an anti-pattern) for <code>a</code> to depend on <code>b</code> while <code>b</code> depends on <code>a</code>. Notationally, we could express this with the <code>&#x3C;=</code> operator, rather than <code>&#x3C;</code>. If <code>a &#x3C;= b</code> and <code>b &#x3C;= a</code>, then it must be the case that <code>a = b</code>, and these two dependencies should be updated at the same time, on the same tier.</p>
<p>This <em>is</em> the case in my real-world system, and the way I handle this is to update any tiers with circular dependencies <em>twice</em>. Here's how that looks</p>
<ul>
<li><code>a v1</code> depends on <code>b v0</code> and <code>b v1</code> depends on <code>a v0</code></li>
<li>update <code>a</code> to depend on <code>b v1</code>, producing <code>a v2</code>; update <code>b</code> to depend on <code>a v1</code>, producing <code>b v2</code></li>
<li>at this point, <code>a v2</code> still (circularly) depends on the "old" <code>a v0</code> via <code>b v1</code>, and vice versa for <code>b v2</code></li>
<li>so update <code>a</code> again to depend on <code>b v2</code>, producing <code>a v3</code>; and update <code>b</code> again to depend on <code>a v2</code>, producing <code>b v3</code></li>
<li>now, we have <code>a v3 &#x3C; b v2 &#x3C; a v1</code> and vice versa for <code>b</code>, and the old dependencies are no longer brought in transitively (at least two levels deep)</li>
</ul>
<p>How does the possibility of circular dependencies affect the minimum required number of tiers? How do we express that, when <code>a &#x3C;= b</code>, for example, but we have no corresponding <code>b &#x3C;= a</code>, that <code>a</code> and <code>b</code> should be in different tiers?</p>
<p>There's a bit more to think about here, but I'll leave that for another time.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[Drop Everything and Review]]></title>
            <link>https://awwsmm.com/blog/drop-everything-and-review</link>
            <guid isPermaLink="false">drop-everything-and-review</guid>
            <pubDate>Mon, 22 Apr 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[On prioritizing code review when developing software]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><h2>The Inner and Outer Development Loops</h2>
<p>Feedback is critical when developing software; the earlier it can be given, the better. Static code analysis tools will <em>immediately</em> write <span style="text-decoration:underline;text-decoration-style:wavy;text-decoration-color: red;">red squigglies</span> underneath code, as it's being written, to let a programmer know that there's a syntax error. (In fact, as I'm writing this blog post, I'm getting blue underlines from my spellchecker.) Unit tests, similarly, give very quick feedback, validating the logic of any newly-written code, and ensuring that there are no regressions (that the new code doesn't cause previously-written tests to break).</p>
<p>This very fast code-build-test feedback loop is often called the <a href="https://sourcegraph.com/blog/developer-productivity-thoughts">inner loop of software development</a>. It requires no input from other people, and the time for a complete loop can be as short as the time it takes static analysis to run, which might be only a few hundred milliseconds. The only blockers in the inner loop are the speed of the compiler or interpreter and the speed at which the developer can program.</p>
<p>The <em>outer loop</em>, by contrast, usually refers to the process of deploying code to a live environment and iterating based on integration with the larger system, acceptance tests, performance tests, and so on (though <a href="https://sourcegraph.com/blog/developer-productivity-thoughts">different</a> sources <a href="https://docs.stakater.com/saap/for-developers/explanation/inner-outer-loop.html">disagree</a> about <a href="https://notes.paulswail.com/public/The+inner+and+outer+loops+of+software+development+workflow">which steps</a> should be included in the <a href="https://www.mckinsey.com/industries/technology-media-and-telecommunications/our-insights/yes-you-can-measure-software-developer-productivity">outer loop</a>). This loop is much more involved and, accordingly, takes much more time to provide feedback to the developer. Depending on how fast your CI / CD pipeline runs, and whether your QA tests are automated or manual, it could take anywhere from minutes to days.</p>
<p>But I propose that there is a <em>middle loop</em>, as well, which often gets incorrectly lumped into the outer loop: the code review loop.</p>
<h2>The Middle Loop</h2>
<p>The Middle Development Loop involves getting feedback from developers and other stakeholders, adjusting your code according to that feedback, and then requesting additional feedback. It is distinct from the inner loop, which is traced by a single developer in a single codebase in a single environment, as well as from the outer loop, which is traced by many developers across many environments. The key differentiator here is that this is the first time that multiple stakeholders will be looking at the same new bit of code.</p>
<p>This often happens during code review, but feedback can come in many forms: pair programming, mob programming, <a href="https://glia.engineering/the-case-for-synchronous-code-reviews-51a19b76b7b7">synchronous code review</a>, as well as traditional asynchronous code review. The latter is, in many workplaces, the standard: you create a PR, add some reviewers, and go off and do something else while you wait for feedback.</p>
<p><img src="/blog/drop-everything-and-review/approvals.png" alt="https://xkcd.com/303/"></p>
<p>This is usually fine, provided you have lots of tasks to work on and can context switch easily from one to another while waiting for reviews. And while this is often the case, in my experience, the opposite happens just as often: you're building some feature across multiple code bases, or in multiple steps, and you need reviews and approvals at each stage. In this case, each time a review is required, it becomes a blocker.</p>
<p>Developers can get frustrated waiting for reviews and glob multiple fixes into a single PR to reduce the number of reviews required, or they might ping other developers directly to ask for reviews. Those pinged might be taken out of their <a href="https://github.blog/2024-01-22-how-to-get-in-the-flow-while-coding-and-why-its-important">flow state</a>, or even feel harassed, if contacted over and over.</p>
<p>For all parties involved, it can be a very frustrating experience.</p>
<p>If you have the power to do so in your organization, push for <a href="https://glia.engineering/the-case-for-synchronous-code-reviews-51a19b76b7b7">synchronous code reviews</a>, which greatly reduce the size of the middle loop, or for synchronous <em>coding</em>, like pair or mob programming, which eliminates the middle loop entirely. For many reading this, though, I know this is not an option. You've got async code reviews and you're stuck with them. In that case, let's try to make the best of a less-than-ideal situation: what is it that makes async review frustrating?</p>
<p>The problem with async code review is that it often unnecessarily inflates the duration of the middle loop.</p>
<p>Code review can be a thankless job. When's the last time you heard of someone getting promoted for being the most thorough reviewer on a team? Plus, it's easy to hide in a crowd, and if 10 developers are added as reviewers to a PR which only needs 2 approvals, they may ignore the request, assuming that their teammates will pick up the slack. Even when a developer <em>does</em> review some code, they may delay doing so. Waiting until you're finished your current task, or until after lunch, or even until after your next meeting, to review a PR may not seem like a delay for you. In fact, in may seem downright prompt. But to the developer waiting for a review to continue their work, they are blocked.</p>
<p>The next time <em>you</em> put up a PR, you will <em>also</em> need reviews. And just like your coworkers, you will want them as quickly as possible. So remember that when someone requests a code review, the courteous thing to do is to <strong>Drop Everything and Review (DEAR)</strong>.</p>
<h2>Minimize the Middle Loop, Dear</h2>
<p>After handling any active production incidents, the first thing on a developer's <span style="white-space: nowrap"> <code>// TODO</code> </span> list should <em>always</em> be reviewing code.</p>
<p>If you've just sat down at your desk and are looking for something to work on, checking which pull requests you've been assigned to should become a reflex.</p>
<p>Don't start that little bug fix, don't read that next blog post (unless it's this one), don't check your inbox.</p>
<p>Remember <strong>DEAR</strong> and do the courteous thing: Drop Everything and Review.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[What Are Const Generics and How Are They Used in Rust?]]></title>
            <link>https://awwsmm.com/blog/what-are-const-generics-and-how-are-they-used-in-rust</link>
            <guid isPermaLink="false">what-are-const-generics-and-how-are-they-used-in-rust</guid>
            <pubDate>Mon, 25 Mar 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Understanding const generics in the Rust programming language with a few examples]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><p><a href="https://github.com/awwsmm/daily-bevy/tree/time/virtual_time">I was working through an example</a> in <a href="https://github.com/bevyengine/bevy/blob/v0.13.0/examples/time/virtual_time.rs">the repo for the Bevy game engine</a> recently and came across this code</p>
<pre><code class="hljs language-rust"><span class="hljs-comment">/// Update the speed of `Time&#x3C;Virtual>.` by `DELTA`</span>
<span class="hljs-keyword">fn</span> <span class="hljs-title function_">change_time_speed</span>&#x3C;<span class="hljs-keyword">const</span> DELTA: <span class="hljs-type">i8</span>>(<span class="hljs-keyword">mut</span> time: ResMut&#x3C;Time&#x3C;Virtual>>) {
    <span class="hljs-keyword">let</span> <span class="hljs-variable">time_speed</span> = (time.<span class="hljs-title function_ invoke__">relative_speed</span>() + DELTA <span class="hljs-keyword">as</span> <span class="hljs-type">f32</span>)
        .<span class="hljs-title function_ invoke__">round</span>()
        .<span class="hljs-title function_ invoke__">clamp</span>(<span class="hljs-number">0.25</span>, <span class="hljs-number">5</span>.);

    <span class="hljs-comment">// set the speed of the virtual time to speed it up or slow it down</span>
    time.<span class="hljs-title function_ invoke__">set_relative_speed</span>(time_speed);
}
</code></pre>
<p>This is a function (<code>fn</code>) which takes a <code>mut</code>able argument called <code>time</code>. The type of <code>time</code>, <code>ResMut&#x3C;Time&#x3C;Virtual>></code>, comes after the colon, <code>:</code>.</p>
<p>The thing that caught my eye here was the generic parameter: <code>&#x3C;const DELTA: i8></code>. What is that?</p>
<p>Here's another example from Bevy</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">pub</span> <span class="hljs-keyword">unsafe</span> <span class="hljs-keyword">fn</span> <span class="hljs-title function_">read</span>&#x3C;T>(<span class="hljs-keyword">self</span>) <span class="hljs-punctuation">-></span> T {
    <span class="hljs-keyword">let</span> <span class="hljs-variable">ptr</span> = <span class="hljs-keyword">self</span>.<span class="hljs-title function_ invoke__">as_ptr</span>().cast::&#x3C;T>().<span class="hljs-title function_ invoke__">debug_ensure_aligned</span>();
    <span class="hljs-comment">// -- snip --</span>
}
</code></pre>
<p>The <code>read</code> function takes a generic type parameter <code>T</code> and uses it in two places: in the body of the function, and as a return type. Programmers who are familiar with generics know that an unconstrained <code>T</code> is a placeholder that means "any type"; it could be <code>String</code> or <code>bool</code> or anything else.</p>
<blockquote>
<p>In languages with a global type hierarchy, like Java, a value <code>t: T</code> has <em>some</em> operations which can be performed on it, like <code>.toString()</code>, because <em>every</em> type <code>T</code> in Java extends the base <code>Object</code> type. Rust has no such global type hierarchy, and no root <code>Object</code> type, so there's not much at all you can do with an instance of an unconstrained type.</p>
</blockquote>
<p>Going back to the first example, <code>const DELTA: i8</code> clearly already <em>has</em> a type, appearing after the colon, <code>:</code>. (It is <code>i8</code>, an 8-bit signed integer.) So what is it doing sitting between those angle brackets (<code>&#x3C;></code>) where generic parameters usually sit?</p>
<p>In this position, <code>const DELTA: i8</code> is acting as a <a href="https://doc.rust-lang.org/reference/items/generics.html#const-generics">const generic</a>.</p>
<h2>What Are Const Generics?</h2>
<p>Const generic parameters are a new (<a href="https://blog.rust-lang.org/2021/02/26/const-generics-mvp-beta.html">ish</a>) kind of generic parameter in Rust, similar to type parameters (e.g. <code>T</code>) and lifetime parameters (e.g. <code>'a</code>). In the same way that a function (or method, <code>struct</code>, <code>enum</code>, <code>impl</code>, <code>trait</code>, or <code>type</code> alias) can use a generic <em>type</em> parameter, it can also use <em>const generic</em> parameters.</p>
<p>Const generic parameters are what power <code>[T; N]</code> type annotation of arrays in Rust. They are why <code>[T; 3]</code> (an array of three <code>T</code> values) and <code>[T; 4]</code> (an array of four <code>T</code> values) are <em>different types</em>, but different types which can be handled <em>generically</em> as specific implementations of <code>[T; N]</code>.</p>
<p>Const generic parameters allow items to be generic over <em>constant values</em>, rather than over types.</p>
<p>The difference can be subtle. Here's a simple example</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">fn</span> <span class="hljs-title function_">add</span>&#x3C;<span class="hljs-keyword">const</span> b: <span class="hljs-type">i8</span>>(a: <span class="hljs-type">i8</span>) <span class="hljs-punctuation">-></span> <span class="hljs-type">i8</span> {
  a + b
}
</code></pre>
<p>Here, <code>b</code> is not a "type parameter"; it is a <em>value</em>, and so it can be treated exactly as a value, used in expressions, and so on. But since it is <code>const</code>, the value of <code>b</code> must be known at compile time. For example, the following will not compile</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">fn</span> <span class="hljs-title function_">example</span>(a: <span class="hljs-type">i8</span>, b: <span class="hljs-type">i8</span>) <span class="hljs-punctuation">-></span> <span class="hljs-type">i8</span> {
    add::&#x3C;b>(a) <span class="hljs-comment">// error: attempt to use a non-constant value in a constant</span>
}
</code></pre>
<p>The logic in this function, of course, could also be expressed like</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">fn</span> <span class="hljs-title function_">add</span>(a: <span class="hljs-type">i8</span>, b: <span class="hljs-type">i8</span>) <span class="hljs-punctuation">-></span> <span class="hljs-type">i8</span> {
  a + b
}
</code></pre>
<p>...so what's the benefit of const generics? Let's look at some other examples</p>
<h2>Using Const Generics to Enforce Correctness</h2>
<p>There are a few examples from linear algebra where const generics are very helpful. For example, the <a href="https://en.wikipedia.org/wiki/Dot_product">dot product</a> of two vectors <code>a</code> and <code>b</code>, is defined for any two vectors of any dimensionality (length), provided they have the <em>same</em> dimensionality</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">struct</span> <span class="hljs-title class_">Vector</span>&#x3C;<span class="hljs-keyword">const</span> N: <span class="hljs-type">usize</span>>([<span class="hljs-type">i32</span>; N]);

<span class="hljs-keyword">impl</span>&#x3C;<span class="hljs-keyword">const</span> N: <span class="hljs-type">usize</span>> Vector&#x3C;N> {
    <span class="hljs-keyword">fn</span> <span class="hljs-title function_">dot</span>(&#x26;<span class="hljs-keyword">self</span>, other: &#x26;Vector&#x3C;N>) <span class="hljs-punctuation">-></span> <span class="hljs-type">i32</span> {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut </span><span class="hljs-variable">result</span> = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">for</span> <span class="hljs-variable">index</span> <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..N {
            result += <span class="hljs-keyword">self</span>.<span class="hljs-number">0</span>[index] * other.<span class="hljs-number">0</span>[index]
        }
        result
    }
}
</code></pre>
<p>We get a compile-time error if we try to find the dot product of two vectors with different numbers of elements</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">fn</span> <span class="hljs-title function_">main</span>() {
    <span class="hljs-keyword">let</span> <span class="hljs-variable">a</span> = <span class="hljs-title function_ invoke__">Vector</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]);
    <span class="hljs-keyword">let</span> <span class="hljs-variable">b</span> = <span class="hljs-title function_ invoke__">Vector</span>([<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]);
    
    <span class="hljs-built_in">assert_eq!</span>(a.<span class="hljs-title function_ invoke__">dot</span>(&#x26;b), <span class="hljs-number">32</span>); <span class="hljs-comment">// ok: a and b have the same length</span>
    
    <span class="hljs-keyword">let</span> <span class="hljs-variable">c</span> = <span class="hljs-title function_ invoke__">Vector</span>([<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]);
    
    a.<span class="hljs-title function_ invoke__">dot</span>(&#x26;c); <span class="hljs-comment">// error: expected `&#x26;Vector&#x3C;3>`, but found `&#x26;Vector&#x3C;4>`</span>
}
</code></pre>
<p>Const generics can be applied to <a href="https://amacal.medium.com/learning-rust-const-generics-8c29fc26fad4">matrix multiplication</a>, as well. Two matrices <a href="https://en.wikipedia.org/wiki/Matrix_multiplication">can be multiplied</a> only if the first one has <code>M</code> rows and <code>N</code> columns and the second has <code>N</code> rows and <code>P</code> columns. The resulting matrix will have <code>M</code> rows and <code>P</code> columns.</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">struct</span> <span class="hljs-title class_">Matrix</span>&#x3C;<span class="hljs-keyword">const</span> nRows: <span class="hljs-type">usize</span>, <span class="hljs-keyword">const</span> nCols: <span class="hljs-type">usize</span>>([[<span class="hljs-type">i32</span>; nCols]; nRows]);

<span class="hljs-keyword">impl</span>&#x3C;<span class="hljs-keyword">const</span> M: <span class="hljs-type">usize</span>, <span class="hljs-keyword">const</span> N: <span class="hljs-type">usize</span>> Matrix&#x3C;M, N> {
    <span class="hljs-keyword">fn</span> <span class="hljs-title function_">multiply</span>&#x3C;<span class="hljs-keyword">const</span> P: <span class="hljs-type">usize</span>>(&#x26;<span class="hljs-keyword">self</span>, other: &#x26;Matrix&#x3C;N, P>) <span class="hljs-punctuation">-></span> Matrix&#x3C;M, P> {
        todo!()
    }
}
</code></pre>
<p>Here, we again get a compile-time error if we ignore this constraint</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">fn</span> <span class="hljs-title function_">main</span>() {
    <span class="hljs-keyword">let</span> <span class="hljs-variable">a</span> = <span class="hljs-title function_ invoke__">Matrix</span>([[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]]); <span class="hljs-comment">// 2 x 3 matrix</span>
    <span class="hljs-keyword">let</span> <span class="hljs-variable">b</span> = <span class="hljs-title function_ invoke__">Matrix</span>([[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>], [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]]); <span class="hljs-comment">// 3 x 4 matrix</span>
    
    a.<span class="hljs-title function_ invoke__">multiply</span>(&#x26;b); <span class="hljs-comment">// ok: 2 x 4 matrix</span>
    
    <span class="hljs-keyword">let</span> <span class="hljs-variable">c</span> = <span class="hljs-title function_ invoke__">Matrix</span>([[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]]); <span class="hljs-comment">// 2 x 3 matrix</span>
    
    a.<span class="hljs-title function_ invoke__">multiply</span>(&#x26;c); <span class="hljs-comment">// error: expected `&#x26;Matrix&#x3C;3, &#x3C;unknown>>`, but found `&#x26;Matrix&#x3C;2, 3>`</span>
}
</code></pre>
<p>These constraints can be enforced at runtime without const generics, but const generics can help <a href="https://en.wikipedia.org/wiki/Shift-left_testing">shift these issues left</a>, catching them earlier in the development process, tightening <a href="https://www.getambassador.io/docs/telepresence/latest/concepts/devloop#what-is-the-inner-dev-loop">the inner dev loop</a>.</p>
<h2>Using Const Generics to Conditionally Implement <code>trait</code>s</h2>
<p>(Adapted from <a href="https://nora.codes/post/its-time-to-get-hyped-about-const-generics-in-rust/">Nora's example here</a>.)</p>
<p>Const generics also enable really powerful patterns, like compile-type checks on values in signatures. For example...</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">struct</span> <span class="hljs-title class_">Assert</span>&#x3C;<span class="hljs-keyword">const</span> COND: <span class="hljs-type">bool</span>> {}
</code></pre>
<p>...this <code>struct</code> takes a constant generic <code>bool</code> parameter, <code>COND</code>. If we define a <code>trait</code> <code>IsTrue</code>...</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">trait</span> <span class="hljs-title class_">IsTrue</span> {}

<span class="hljs-keyword">impl</span> <span class="hljs-title class_">IsTrue</span> <span class="hljs-keyword">for</span> <span class="hljs-title class_">Assert</span>&#x3C;<span class="hljs-literal">true</span>> {}
</code></pre>
<p>...we can conditionally implement <code>trait</code>s by requiring some <code>Assert</code> to <code>impl IsTrue</code>, like so</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">trait</span> <span class="hljs-title class_">IsOdd</span>&#x3C;<span class="hljs-keyword">const</span> N: <span class="hljs-type">i32</span>> {}

<span class="hljs-keyword">impl</span>&#x3C;<span class="hljs-keyword">const</span> N: <span class="hljs-type">i32</span>> IsOdd&#x3C;N> <span class="hljs-keyword">for</span> <span class="hljs-title class_">i32</span> <span class="hljs-keyword">where</span> Assert&#x3C;{N % <span class="hljs-number">2</span> == <span class="hljs-number">1</span>}>: IsTrue {}
</code></pre>
<blockquote>
<p>The above <code>Assert&#x3C;{N % 2 == 1}></code> requires <span style="white-space: nowrap;"><code>#![feature(generic_const_exprs)]</code></span> and the <code>nightly</code> toolchain. See <a href="https://github.com/rust-lang/rust/issues/76560">https://github.com/rust-lang/rust/issues/76560</a> for more info.</p>
</blockquote>
<p>Above, <code>trait IsOdd</code> is implemented for the <code>i32</code> type, but only on values <code>N</code> which satisfy <code>N % 2 == 1</code>. We can use this trait to get compile-time checks that constant (hard-coded) <code>i32</code> values are odd</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">fn</span> <span class="hljs-title function_">do_something_odd</span>&#x3C;<span class="hljs-keyword">const</span> N: <span class="hljs-type">i32</span>>() <span class="hljs-keyword">where</span> <span class="hljs-type">i32</span>: IsOdd&#x3C;N> {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"oogabooga!"</span>)
}

<span class="hljs-keyword">fn</span> <span class="hljs-title function_">do_something</span>() {
    do_something_odd::&#x3C;<span class="hljs-number">19</span>>();
    do_something_odd::&#x3C;<span class="hljs-number">42</span>>(); <span class="hljs-comment">// does not compile</span>
    do_something_odd::&#x3C;<span class="hljs-number">7</span>>();
    do_something_odd::&#x3C;<span class="hljs-number">64</span>>(); <span class="hljs-comment">// does not compile</span>
    do_something_odd::&#x3C;<span class="hljs-number">8</span>>(); <span class="hljs-comment">// does not compile</span>
}
</code></pre>
<p>The above will generate a compiler error like</p>
<pre><code class="hljs language-rust">error[E0308]: mismatched types
  -<span class="hljs-punctuation">-></span> src/main.rs:<span class="hljs-number">70</span>:<span class="hljs-number">5</span>
   |
<span class="hljs-number">70</span> |     do_something_odd::&#x3C;<span class="hljs-number">42</span>>();
   |     ^^^^^^^^^^^^^^^^^^^^^^^^ expected `<span class="hljs-literal">false</span>`, found `<span class="hljs-literal">true</span>`
   |
   = note: expected constant `<span class="hljs-literal">false</span>`
              found constant `<span class="hljs-literal">true</span>`
</code></pre>
<h2>Using Const Generics to Avoid Complex Return Types</h2>
<p>Finally, const generics can be used to make code more readable, and more performant. The example from the beginning of this post comes from Bevy, and the reason const generics are used there is because Bevy is expecting a function pointer as an argument to a method</p>
<pre><code class="hljs language-rust"><span class="hljs-keyword">fn</span> <span class="hljs-title function_">main</span>() {
    App::<span class="hljs-title function_ invoke__">new</span>()
        <span class="hljs-comment">// -- snip --</span>
        .<span class="hljs-title function_ invoke__">add_systems</span>(
            Update,
            (
                <span class="hljs-comment">// -- snip --</span>
                change_time_speed::&#x3C;<span class="hljs-number">1</span>>.<span class="hljs-title function_ invoke__">run_if</span>(<span class="hljs-title function_ invoke__">input_just_pressed</span>(KeyCode::ArrowUp)),
                <span class="hljs-comment">// -- snip --</span>
            ),
        )
        .<span class="hljs-title function_ invoke__">run</span>();
}
</code></pre>
<p><code>change_time_speed::&#x3C;1></code>, above, is a function pointer. We can rearrange this method to take an argument, rather than using a const generic parameter...</p>
<pre><code class="hljs language-rust"><span class="hljs-title function_ invoke__">change_time_speed_2</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_ invoke__">run_if</span>(<span class="hljs-title function_ invoke__">input_just_pressed</span>(KeyCode::ArrowUp)),
</code></pre>
<p>...but then we would have to change the return type as well</p>
<pre><code class="hljs language-rust"><span class="hljs-comment">/// Update the speed of `Time&#x3C;Virtual>.` by `DELTA`</span>
<span class="hljs-keyword">fn</span> <span class="hljs-title function_">change_time_speed_2</span>(delta: <span class="hljs-type">i8</span>) <span class="hljs-punctuation">-></span> <span class="hljs-keyword">impl</span> <span class="hljs-title class_">FnMut</span>(ResMut&#x3C;Time&#x3C;Virtual>>) {
    <span class="hljs-keyword">move</span> |<span class="hljs-keyword">mut</span> time| {
        <span class="hljs-keyword">let</span> <span class="hljs-variable">time_speed</span> = (time.<span class="hljs-title function_ invoke__">relative_speed</span>() + delta <span class="hljs-keyword">as</span> <span class="hljs-type">f32</span>)
            .<span class="hljs-title function_ invoke__">round</span>()
            .<span class="hljs-title function_ invoke__">clamp</span>(<span class="hljs-number">0.25</span>, <span class="hljs-number">5</span>.);

        <span class="hljs-comment">// set the speed of the virtual time to speed it up or slow it down</span>
        time.<span class="hljs-title function_ invoke__">set_relative_speed</span>(time_speed);
    }
}
</code></pre>
<p>To many, the original function may be more readable</p>
<pre><code class="hljs language-rust"><span class="hljs-comment">/// Update the speed of `Time&#x3C;Virtual>.` by `DELTA`</span>
<span class="hljs-keyword">fn</span> <span class="hljs-title function_">change_time_speed</span>&#x3C;<span class="hljs-keyword">const</span> DELTA: <span class="hljs-type">i8</span>>(<span class="hljs-keyword">mut</span> time: ResMut&#x3C;Time&#x3C;Virtual>>) {
    <span class="hljs-keyword">let</span> <span class="hljs-variable">time_speed</span> = (time.<span class="hljs-title function_ invoke__">relative_speed</span>() + DELTA <span class="hljs-keyword">as</span> <span class="hljs-type">f32</span>)
        .<span class="hljs-title function_ invoke__">round</span>()
        .<span class="hljs-title function_ invoke__">clamp</span>(<span class="hljs-number">0.25</span>, <span class="hljs-number">5</span>.);

    <span class="hljs-comment">// set the speed of the virtual time to speed it up or slow it down</span>
    time.<span class="hljs-title function_ invoke__">set_relative_speed</span>(time_speed);
}
</code></pre>
<p>Remember, as well, that Rust uses <a href="https://doc.rust-lang.org/book/ch10-01-syntax.html#performance-of-code-using-generics">monomorphization of generics</a> to improve runtime performance. So not only is the const generic version of this function more readable, but it's possible (though I haven't benchmarked) that it's more performant as well. Either way, it's good to know that there are multiple ways to attack a problem, and to be able to weigh the pros and cons of each approach.</p>
<p>Hopefully this discussion has helped you to understand what const generics are, and how they can be used in Rust.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[Make Invalid States Unrepresentable]]></title>
            <link>https://awwsmm.com/blog/make-invalid-states-unrepresentable</link>
            <guid isPermaLink="false">make-invalid-states-unrepresentable</guid>
            <pubDate>Thu, 01 Feb 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Let the compiler do the hard work of data validation for you]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><p>Suppose you have a <code>Person</code> class in your program, and that a <code>Person</code> has an <code>age</code>. What type should the <code>age</code> be?</p>
<h2><code>age</code> as a <code>String</code></h2>
<pre><code class="hljs language-scala"><span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>(<span class="hljs-params">age: <span class="hljs-type">String</span></span>)</span>
</code></pre>
<p>"Of course it shouldn't be a <code>String</code>" you might think. But why? The reason is that we can then end up with code like</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">val</span> person = <span class="hljs-type">Person</span>(<span class="hljs-string">"Jeff"</span>)
</code></pre>
<p>If we ever wanted to <em>do</em> anything with an <code>age: String</code>, we would need to validate it everywhere</p>
<pre><code class="hljs language-scala"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">isOldEnoughToSmoke</span></span>(person: <span class="hljs-type">Person</span>): <span class="hljs-type">Boolean</span> = {
  <span class="hljs-type">Try</span>(person.age.toInt) <span class="hljs-keyword">match</span> {
    <span class="hljs-keyword">case</span> <span class="hljs-type">Failure</span>(_) => <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-type">Exception</span>(<span class="hljs-string">s"cannot parse age '<span class="hljs-subst">${person.age}</span>' as numeric"</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-type">Success</span>(value) => value >= <span class="hljs-number">18</span>
  }
}

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">isOldEnoughToDrink</span></span>(person: <span class="hljs-type">Person</span>): <span class="hljs-type">Boolean</span> = {
  <span class="hljs-type">Try</span>(person.age.toInt) <span class="hljs-keyword">match</span> {
    <span class="hljs-keyword">case</span> <span class="hljs-type">Failure</span>(_) => <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-type">Exception</span>(<span class="hljs-string">s"cannot parse age '<span class="hljs-subst">${person.age}</span>' as numeric"</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-type">Success</span>(value) => value >= <span class="hljs-number">21</span>
  }
}

<span class="hljs-comment">// etc.</span>
</code></pre>
<p>This is cumbersome for the programmer <em>writing</em> the code, and makes it difficult for any programmer <em>reading</em> the code, as well.</p>
<p>We could move this validation to a separate method</p>
<pre><code class="hljs language-scala"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">parseAge</span></span>(age: <span class="hljs-type">String</span>): <span class="hljs-type">Int</span> = {
  <span class="hljs-type">Try</span>(age.toInt) <span class="hljs-keyword">match</span> {
    <span class="hljs-keyword">case</span> <span class="hljs-type">Failure</span>(_) => <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-type">Exception</span>(<span class="hljs-string">s"cannot parse age '<span class="hljs-subst">$age</span>' as numeric"</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-type">Success</span>(value) => value
  }
}

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">isOldEnoughToSmoke</span></span>(person: <span class="hljs-type">Person</span>): <span class="hljs-type">Boolean</span> =
  parseAge(person.age) >= <span class="hljs-number">18</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">isOldEnoughToDrink</span></span>(person: <span class="hljs-type">Person</span>): <span class="hljs-type">Boolean</span> =
  parseAge(person.age) >= <span class="hljs-number">21</span>
</code></pre>
<p>...but this is still not ideal. The code is a bit cleaner, but we still need to parse a <code>String</code> into an <code>Int</code> every time we want to do anything numeric (comparison, arithmetic, etc.) with the <code>age</code>. This is often called <a href="https://en.wiktionary.org/wiki/stringly-typed">"stringly-typed" data</a>.</p>
<p>This can also move the program into an illegal state by throwing an <code>Exception</code>. If we're going to fail anyway, we should <a href="https://www.martinfowler.com/ieeeSoftware/failFast.pdf">fail fast</a>. We can do better.</p>
<h2><code>age</code> as an <code>Int</code></h2>
<p>Your first instinct might have been to make <code>age</code> an <code>Int</code>, rather than a <code>String</code></p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>(<span class="hljs-params">age: <span class="hljs-type">Int</span></span>)</span>
</code></pre>
<p>If so, you have good instincts. An <code>age: Int</code> is much nicer to work with</p>
<pre><code class="hljs language-scala"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">isOldEnoughToSmoke</span></span>(person: <span class="hljs-type">Person</span>): <span class="hljs-type">Boolean</span> =
  person.age >= <span class="hljs-number">18</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">isOldEnoughToDrink</span></span>(person: <span class="hljs-type">Person</span>): <span class="hljs-type">Boolean</span> =
  person.age >= <span class="hljs-number">21</span>
</code></pre>
<p>This</p>
<ul>
<li>is easier to write</li>
<li>is easier to read</li>
<li>fails fast</li>
</ul>
<p>You <em>cannot construct</em> an instance of the  <code>Person</code> class with a <code>String</code> <code>age</code> now. That is an invalid state. We have <a href="https://www.cs.rice.edu/~javaplt/411/23-spring/NewReadings/functional_programming_on_Wall_Street.pdf">made it unrepresentable</a>, using the type system. The compiler will not allow this program to compile.</p>
<p>Problem solved, right?</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">val</span> person = <span class="hljs-type">Person</span>(<span class="hljs-number">-1</span>)
</code></pre>
<p>This is clearly an invalid state as well. A person cannot have a negative age.</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">val</span> person = <span class="hljs-type">Person</span>(<span class="hljs-number">90210</span>)
</code></pre>
<p>This is also invalid -- it looks like someone accidentally entered their <a href="https://en.wikipedia.org/wiki/Beverly_Hills,_California">ZIP code</a> instead of their age.</p>
<p>So how can we constrain this type even further? How can we make even more invalid states unrepresentable?</p>
<h2><code>age</code> as an <code>Int</code> with constraints</h2>
<h3>at runtime</h3>
<p>We can enforce <em>runtime constraints</em> in any statically-typed language</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>(<span class="hljs-params">age: <span class="hljs-type">Int</span></span>) </span>{
  assert(age >= <span class="hljs-number">0</span> &#x26;&#x26; age &#x3C; <span class="hljs-number">150</span>)
}
</code></pre>
<p>In Scala, <code>assert</code> will throw a <code>java.lang.AssertionError</code> if the assertion fails.</p>
<p>Now we can be sure that the <code>age</code> for any <code>Person</code> will always be within the range <code>[0, 150)</code>. Both</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">val</span> person = <span class="hljs-type">Person</span>(<span class="hljs-number">-1</span>)
</code></pre>
<p>and</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">val</span> person = <span class="hljs-type">Person</span>(<span class="hljs-number">90210</span>)
</code></pre>
<p>will now fail. But they will fail at runtime, halting the execution of our program.</p>
<p>This is similar to what we saw in "<code>age</code> as a <code>String</code>", above. This is still not ideal. Is there a better way?</p>
<h3>at compile time</h3>
<p>Many languages allow <em>compile-time</em> constraints, as well. Usually this is accomplished through macros, which inspect the source code during a compilation phase. These are often referred to as <a href="https://en.wikipedia.org/wiki/Refinement_type">refined types</a>.</p>
<p>Scala has <a href="https://blog.rockthejvm.com/refined-types/">quite good</a> support for <a href="https://github.com/Iltotore/iron">refined types</a> across multiple libraries. A solution using the <a href="https://github.com/fthomas/refined"><code>refined</code> library</a> might look something like</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>(<span class="hljs-params">age: <span class="hljs-type">Int</span> <span class="hljs-type">Refined</span> <span class="hljs-type">GreaterEqual</span>[0] <span class="hljs-type">And</span> <span class="hljs-type">Less</span>[150]</span>)</span>
</code></pre>
<p>A limitation of this approach is that the field(s) to be constrained at compile-time must be <a href="https://en.wikipedia.org/wiki/Literal_(computer_programming)"><em>literal</em>, hard-coded</a> values. Compile-time constraints cannot be enforced on, for example, values provided by a user. By that point, the program has already been compiled. In this case, we can always fall back to runtime constraints, which is often what these libraries do.</p>
<p>For now, we'll continue with runtime constraints only, since often that's the best we can do.</p>
<h2><code>age</code> as an <code>Age</code> with constraints</h2>
<p>From simplest to most complex implementation, we moved left to right in the diagram below</p>
<pre><code>String => Int => Int with constraints
</code></pre>
<p>This increase in complexity directly correlates with the <em>accuracy</em> with which we're modelling this data</p>
<blockquote>
<p>"The problems tackled have inherent complexity, and it takes some effort to model them appropriately." <a href="https://fasterthanli.me/articles/i-want-off-mr-golangs-wild-ride">[source]</a></p>
</blockquote>
<p>The move left-to-right above should be driven by the requirements of your system. You should not implement compile-time refinements, for example, unless you have lots of hard-coded values to validate at compile time: otherwise <a href="https://martinfowler.com/bliki/Yagni.html">you aren't gonna need it</a>. Every line of code has a cost to implement and maintain. Avoiding premature specification is just as important as avoiding <a href="https://www.codewithjason.com/premature-generalization">premature generalization</a>, though it's <strong><em>always easier</em> to move from more specific types to less specific types</strong>, so prefer specificity over generalization.</p>
<p>Every bit of data has a <em>context</em>, as well. There is no such thing as a "pure" <code>Int</code> value floating around in the universe. An age can be modelled as an <code>Int</code>, but it's different from a weight, which could also be modelled as an Int. The labels we attach to these raw values are the <em>context</em></p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>(<span class="hljs-params">age: <span class="hljs-type">Int</span>, weight: <span class="hljs-type">Int</span></span>) </span>{
  assert(age >= <span class="hljs-number">0</span> &#x26;&#x26; age &#x3C; <span class="hljs-number">150</span>)
  assert(weight >= <span class="hljs-number">0</span> &#x26;&#x26; weight &#x3C; <span class="hljs-number">500</span>)
}
</code></pre>
<p>There is one more problem for us to solve here. Suppose I'm 81kg and 33 years old</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">val</span> me = <span class="hljs-type">Person</span>(<span class="hljs-number">81</span>, <span class="hljs-number">33</span>)
</code></pre>
<p>That compiles, but... it shouldn't. I swapped my weight and age!</p>
<p>An easy way to avoid this confusion is to define some more types. In this case, <a href="https://doc.rust-lang.org/rust-by-example/generics/new_types.html"><em>newtypes</em></a></p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Age</span>(<span class="hljs-params">years: <span class="hljs-type">Int</span></span>) </span>{
  assert(years >= <span class="hljs-number">0</span> &#x26;&#x26; years &#x3C; <span class="hljs-number">150</span>)
}

<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Weight</span>(<span class="hljs-params">kgs: <span class="hljs-type">Int</span></span>) </span>{
  assert(kgs >= <span class="hljs-number">0</span> &#x26;&#x26; kgs &#x3C; <span class="hljs-number">500</span>)
}

<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>(<span class="hljs-params">age: <span class="hljs-type">Age</span>, weight: <span class="hljs-type">Weight</span></span>)</span>
</code></pre>
<p>The name <em>newtype</em> for this pattern <a href="https://wiki.haskell.org/Newtype">comes from Haskell</a>. This is a simple way to ensure that we don't accidentally swap values with the same underlying type. The following, for example, will not compile</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">val</span> age = <span class="hljs-type">Age</span>(<span class="hljs-number">33</span>)
<span class="hljs-keyword">val</span> weight = <span class="hljs-type">Weight</span>(<span class="hljs-number">81</span>)

<span class="hljs-keyword">val</span> me = <span class="hljs-type">Person</span>(weight, age) <span class="hljs-comment">// does not compile!</span>
</code></pre>
<p>We could also use <a href="https://medium.com/iterators/to-tag-a-type-88dc344bb66c"><em>tagged types</em></a>. In Scala, the simplest possible example of this looks something like</p>
<pre><code class="hljs language-scala"><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">AgeTag</span></span>
<span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Age</span> </span>= <span class="hljs-type">Int</span> <span class="hljs-keyword">with</span> <span class="hljs-type">AgeTag</span>

<span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">Age</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">apply</span></span>(years: <span class="hljs-type">Int</span>): <span class="hljs-type">Age</span> = {
    assert(years >= <span class="hljs-number">0</span> &#x26;&#x26; years &#x3C; <span class="hljs-number">150</span>)
    years.asInstanceOf[<span class="hljs-type">Age</span>]
  }
}

<span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">WeightTag</span></span>
<span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Weight</span> </span>= <span class="hljs-type">Int</span> <span class="hljs-keyword">with</span> <span class="hljs-type">WeightTag</span>

<span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">Weight</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">apply</span></span>(kgs: <span class="hljs-type">Int</span>): <span class="hljs-type">Weight</span> = {
    assert(kgs >= <span class="hljs-number">0</span> &#x26;&#x26; kgs &#x3C; <span class="hljs-number">500</span>)
    kgs.asInstanceOf[<span class="hljs-type">Weight</span>]
  }
}

<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>(<span class="hljs-params">age: <span class="hljs-type">Age</span>, weight: <span class="hljs-type">Weight</span></span>)</span>

<span class="hljs-keyword">val</span> p0 = <span class="hljs-type">Person</span>(<span class="hljs-number">42</span>, <span class="hljs-number">42</span>) <span class="hljs-comment">// does not compile -- an Int is not an Age</span>
<span class="hljs-keyword">val</span> p1 = <span class="hljs-type">Person</span>(<span class="hljs-type">Age</span>(<span class="hljs-number">42</span>), <span class="hljs-number">42</span>) <span class="hljs-comment">// does not compile -- an Int is not a Weight	</span>
<span class="hljs-keyword">val</span> p2 = <span class="hljs-type">Person</span>(<span class="hljs-type">Age</span>(<span class="hljs-number">42</span>), <span class="hljs-type">Weight</span>(<span class="hljs-number">42</span>)) <span class="hljs-comment">// compiles!</span>
<span class="hljs-keyword">val</span> p3 = <span class="hljs-type">Person</span>(<span class="hljs-type">Weight</span>(<span class="hljs-number">42</span>), <span class="hljs-type">Weight</span>(<span class="hljs-number">42</span>)) <span class="hljs-comment">// does not compile -- a Weight is not an Age</span>
</code></pre>
<p>This makes use of the fact that function application <code>f()</code> is syntactic sugar in Scala for an <code>apply()</code> method. So <code>f()</code> is equivalent to <code>f.apply()</code>.</p>
<p>This approach allows us to model the idea that an <code>Age</code> / a <code>Weight</code> is an <code>Int</code>, but an <code>Int</code> is not an <code>Age</code> / a <code>Weight</code>. This means we can treat an <code>Age</code> / a <code>Weight</code> <em>as</em> an <code>Int</code> and add, subtract, or do whatever other <code>Int</code>-like things we want to do.</p>
<p>Mixing these two approaches in one example, you can see the difference between newtypes and tagged types. You must extract the "raw value" from a newtype. You do not need to do this with a tagged type</p>
<pre><code class="hljs language-scala"><span class="hljs-comment">// `Age` is a tagged type</span>
<span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">AgeTag</span></span>
<span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Age</span> </span>= <span class="hljs-type">Int</span> <span class="hljs-keyword">with</span> <span class="hljs-type">AgeTag</span>

<span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">Age</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">apply</span></span>(years: <span class="hljs-type">Int</span>): <span class="hljs-type">Age</span> = {
    assert(years >= <span class="hljs-number">0</span> &#x26;&#x26; years &#x3C; <span class="hljs-number">150</span>)
    years.asInstanceOf[<span class="hljs-type">Age</span>]
  }
}

<span class="hljs-comment">// `Weight` is a newtype</span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Weight</span>(<span class="hljs-params">kgs: <span class="hljs-type">Int</span></span>) </span>{
  assert(kgs >= <span class="hljs-number">0</span> &#x26;&#x26; kgs &#x3C; <span class="hljs-number">500</span>)
}

<span class="hljs-comment">// `Age`s can be treated as `Int`s, because they _are_ `Int`s</span>
assert(<span class="hljs-number">40</span> == <span class="hljs-type">Age</span>(<span class="hljs-number">10</span>) + <span class="hljs-type">Age</span>(<span class="hljs-number">30</span>))

<span class="hljs-comment">// `Weight`s are not `Int`s, they _contain_ `Int`s</span>
<span class="hljs-type">Weight</span>(<span class="hljs-number">10</span>) + <span class="hljs-type">Weight</span>(<span class="hljs-number">30</span>) <span class="hljs-comment">// does not compile</span>

<span class="hljs-comment">// To add `Weight`s, we must "unwrap" them</span>
<span class="hljs-type">Weight</span>(<span class="hljs-number">10</span>).kgs + <span class="hljs-type">Weight</span>(<span class="hljs-number">30</span>).kgs
</code></pre>
<p>In some languages, the "unwrapping" of newtypes can be done automatically. This can make newtypes as ergonomic as tagged types. For example, in Scala, this could be done with an <em>implicit conversion</em></p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">implicit</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">weightAsInt</span></span>(weight: <span class="hljs-type">Weight</span>): <span class="hljs-type">Int</span> = weight.kgs

<span class="hljs-comment">// `Weight`s are not `Int`s, but they can be _converted_ to `Int`s</span>
<span class="hljs-type">Weight</span>(<span class="hljs-number">10</span>) + <span class="hljs-type">Weight</span>(<span class="hljs-number">30</span>) <span class="hljs-comment">// this now compiles</span>
</code></pre>
<h2>Further refinements</h2>
<p>The important point of the above discussion is that, as much as possible, we want to <em>make invalid states unrepresentable</em>.</p>
<ul>
<li>"Jeff" is an invalid age. Age isn't a string, it is a number.</li>
<li>-1 is an invalid age. Age cannot be negative, it should be 0 or positive, and probably less than about 150.</li>
<li>My age is not 88. An age should be easily distinguishable from other integral values, like weight.</li>
</ul>
<p>Everything discussed above implemented these refinements on the concept of "age", one at a time.</p>
<p>We can make further refinements if there is a need for those refinements.</p>
<p>For example, suppose we want to send a "Happy Birthday!" email to a <code>Person</code> on their birthday. Rather than an <code>Age</code>, we now need a date of birth.</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Date</span>(<span class="hljs-params">year: <span class="hljs-type">Year</span>, month: <span class="hljs-type">Month</span>, day: <span class="hljs-type">Day</span></span>)</span>

<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Year</span>(<span class="hljs-params">value: <span class="hljs-type">Int</span>, currentYear: <span class="hljs-type">Int</span></span>) </span>{
  assert(value >= <span class="hljs-number">1900</span> &#x26;&#x26; value &#x3C;= currentYear)
}

<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Month</span>(<span class="hljs-params">value: <span class="hljs-type">Int</span></span>) </span>{
  assert(value >= <span class="hljs-number">1</span> &#x26;&#x26; value &#x3C;= <span class="hljs-number">12</span>)
}

<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Day</span>(<span class="hljs-params">value: <span class="hljs-type">Int</span></span>) </span>{
  assert(value >= <span class="hljs-number">1</span> &#x26;&#x26; value &#x3C;= <span class="hljs-number">31</span>)
}

<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>(<span class="hljs-params">dateOfBirth: <span class="hljs-type">Date</span>, weight: <span class="hljs-type">Weight</span></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">age</span></span>(currentDate: <span class="hljs-type">Date</span>): <span class="hljs-type">Age</span> = {
    ??? <span class="hljs-comment">// TODO calculate Age from dateOfBirth</span>
  }
}
</code></pre>
<p>The amount of information provided by <code>dateOfBirth</code> is strictly greater than the amount of information provided by <code>Age</code>. We can calculate someone's age from their date of birth, but we cannot do the opposite.</p>
<p>The above implementation leaves much to be desired, though -- there are lots of invalid states. A better way to implement this would be for <code>Month</code> to be an enum, and for <code>Day</code> validity to depend on the <code>Month</code> (February never has 30 days, for example)</p>
<pre><code class="hljs language-scala"><span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Year</span>(<span class="hljs-params">value: <span class="hljs-type">Int</span>, currentYear: <span class="hljs-type">Int</span></span>) </span>{
  assert(value >= <span class="hljs-number">1900</span> &#x26;&#x26; value &#x3C;= currentYear)
}

<span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Month</span></span>

<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">January</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">February</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">March</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">April</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">May</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">June</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">July</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">August</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">September</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">October</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">November</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>
<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">December</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Month</span></span>

<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Day</span>(<span class="hljs-params">value: <span class="hljs-type">Int</span>, month: <span class="hljs-type">Month</span></span>) </span>{
  month <span class="hljs-keyword">match</span> {
    <span class="hljs-keyword">case</span> <span class="hljs-type">February</span> => assert(value >= <span class="hljs-number">1</span> &#x26;&#x26; value &#x3C;= <span class="hljs-number">28</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-type">April</span> | <span class="hljs-type">June</span> | <span class="hljs-type">September</span> | <span class="hljs-type">November</span> => assert(value >= <span class="hljs-number">1</span> &#x26;&#x26; value &#x3C;= <span class="hljs-number">30</span>)
    <span class="hljs-keyword">case</span> _ => assert(value >= <span class="hljs-number">1</span> &#x26;&#x26; value &#x3C;= <span class="hljs-number">31</span>)
  }
}

<span class="hljs-keyword">case</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Date</span>(<span class="hljs-params">year: <span class="hljs-type">Year</span>, month: <span class="hljs-type">Month</span>, day: <span class="hljs-type">Day</span></span>)</span>
</code></pre>
<p>Always prefer low-cardinality types to <a href="https://www.seas.upenn.edu/~sweirich/types/archive/1999-2003/msg01233.html">high-cardinality types</a>, when possible. It limits the number of possible invalid states. In most languages, <code>enum</code>s are the way to go here (in Scala 2, an <code>enum</code> can be modelled using a <code>sealed trait</code>, as shown above). But there are still invalid states hiding above. Can you find them?</p>
<p>In some cases, stringly-typed data validated using regular expressions can be replaced entirely by <code>enum</code>s. Could you model <a href="https://www150.statcan.gc.ca/n1/pub/92-153-g/2011002/tech-eng.htm">Canadian postal codes</a> such that it's impossible to construct an invalid one?</p>
<p>Use the above knowledge to go forth and <em>make invalid states unrepresentable</em>.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[What This Senior Developer Learned From His First Big Rust Project]]></title>
            <link>https://awwsmm.com/blog/what-this-senior-developer-learned-from-his-first-big-rust-project</link>
            <guid isPermaLink="false">what-this-senior-developer-learned-from-his-first-big-rust-project</guid>
            <pubDate>Mon, 08 Jan 2024 00:00:00 GMT</pubDate>
            <description><![CDATA[Building a Rust IoT MVP over the Holidays]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><p>Here is a bit of background on me</p>
<ul>
<li>according to my company's org chart on Workday, my current title is "Senior Consultant"</li>
<li>I've been writing code full-time in various capacities for over a decade and I've been professionally developing software for about five years</li>
<li>in graduate school, I did data analysis and visualization almost entirely in C++</li>
<li>for the last four years, my primary development language has been Scala</li>
</ul>
<p>This blend of "close-to-the-metal" development in C++ and FP-style development in Scala has led me to Rust, which I see as a pretty usable middle ground between the two. So over the past year I've been learning Rust by building small projects and leading <a href="https://github.com/rust-book-club">weekly book clubs</a>.</p>
<p>Over the holidays, I decided to take this a step further and build <a href="https://github.com/awwsmm/rust-mvp">my first "big" Rust project</a>. Here's how that went down...</p>
<blockquote>
<p>TL;DR: if you're only interested in the technical discussion, and not so much the project background, skip to the section on <a href="#implementation">implementation</a>. If you just want my conclusions, skip to <a href="#conclusion">the end</a>.</p>
</blockquote>
<h2>The Project</h2>
<blockquote>
<p><a href="https://github.com/awwsmm/rust-mvp">https://github.com/awwsmm/rust-mvp</a></p>
</blockquote>
<p>The idea I had was to build a small Internet of Things (IoT) system. The explicit goals of the project were</p>
<ul>
<li>to build some services which used very few resources, capable of running in environments where the size of the Java Runtime Environment (JRE) would make Scala or Java development impossible</li>
<li>the services should run on separate nodes and somehow discover each other on the network, without the need for hard-coded IPs</li>
<li>the services should be able to send messages to (and receive messages from) one another</li>
<li>there should be some simulated data in the system, which can be visualized (or, at least, exported to a spreadsheet for visualization)</li>
</ul>
<p>In addition, I work for a consulting company, and the client we are engaged with was OOO over Christmas. So another goal of this project was to have all of this completed, from scratch, in just five working days.</p>
<p>I managed to recruit two other developers* who helped build some of the foundations of the project in those first five days; in the two weeks since, I've built out the rest of the project by myself. In general, I consider the effort a success, but am hoping that whoever reads this might be able to leave some valuable feedback which could improve future efforts of this kind.</p>
<blockquote>
<p>* Huge shout-out to <a href="https://github.com/boniface">boniface</a> and <a href="https://github.com/davidleacock">davidleacock</a>!</p>
</blockquote>
<h2>Planning</h2>
<p>The other two developers and I spent the week before Christmas planning and discussing the project, but not coding. We were hoping that "team of three developers builds a Rust IoT MVP in just five days" would be an effective sales tool for ourselves and our company. It was very ambitious, and the work soon spilled over into about four person-weeks total (which is still not bad, if you ask me).</p>
<p>I prepped by writing some <a href="https://github.com/rust-sketches"><em>sketches</em></a>, as I called them. These were little projects that (I'd hoped) would become the building blocks of our MVP. These sketches included</p>
<ul>
<li><a href="https://github.com/rust-sketches/ci-github-actions">learning how to build a CI pipeline in GitHub Actions</a></li>
<li><a href="https://github.com/rust-sketches/cd-github-actions">learning how to build a CD pipeline in GitHub Actions</a></li>
<li><a href="https://github.com/rust-sketches/ping-pong-containers">writing two containerized services in Rust which communicated with each other over a network</a></li>
<li><a href="https://github.com/rust-sketches/ping-pong-mdns">writing two containerized services which discovered each other via mDNS</a></li>
</ul>
<blockquote>
<p>I also created <a href="https://hub.docker.com/r/awwsmm/rust-ci/tags">a custom Rust-based container image</a> for the CD project, which <a href="https://github.com/rust-sketches/cd-github-actions/blob/main/Dockerfile">includes the necessary libraries for the CI project</a>, like <code>rustfmt</code> for formatting, <code>clippy</code> for linting, and <code>grcov</code> for code coverage reporting.</p>
</blockquote>
<p>While I originally thought of containerizing these applications, running them in Kubernetes (K8s), and letting K8s do the service discovery, I realized that that approach wouldn't square with "real life", where the services would somehow have to discover each other on a <a href="https://en.wikipedia.org/wiki/Local_area_network">LAN</a>. <a href="https://en.wikipedia.org/wiki/Multicast_DNS">mDNS</a> seemed the best choice to emulate real-life service discovery on a network.</p>
<p>Finally, we had to plan the domain itself. We came up with something quite similar to <a href="https://bridgera.com/wp-content/uploads/2018/10/IoTeBook3.pdf#page=16">this example from Bridgera</a></p>
<p><img src="/blog/what-this-senior-developer-learned-from-his-first-big-rust-project/iot-flow.png" alt="Diagram of the flow of data through IoT devices, from a sensor, to a control center, to an actuator."></p>
<ol>
<li>a <code>Sensor</code> collects data from the <code>Environment</code>, and somehow communicates that data to...</li>
<li>a <code>Controller</code>, which assesses that data and (optionally) sends a <code>Command</code> to...</li>
<li>an <code>Actuator</code>, which has some effect on...</li>
<li>the <code>Environment</code>, which, in our example, generates fake data and has some internal state which can be modified via <code>Actuator</code> <code>Command</code>s</li>
</ol>
<p>These four kinds of <code>Device</code>s -- <code>Sensor</code>s, <code>Actuator</code>s, and the <code>Controller</code> and <code>Environment</code>, are the <em>services</em> in this system. They connect to each other via mDNS.</p>
<p>As we were short on time and resources, all of this was to be done in software, with no actual interaction with any hardware sensors or actuators. Because of this, we needed a simulated <code>Environment</code>, which could generate fake data for our <code>Sensor</code>s.</p>
<blockquote>
<p>From the outset, we realized it was important to have <a href="https://martinfowler.com/bliki/UbiquitousLanguage.html">Ubiquitous Language</a> around these concepts. We worked to refine and document our understanding of the domain, and keep our model as clear and as small as possible. Nothing unnecessary or confusing should sneak through.</p>
</blockquote>
<p><a name="implementation"></a></p>
<h2>Implementing</h2>
<p>Anyway, down to the nitty-gritty.</p>
<h3>Cargo Workspace</h3>
<p><a href="https://github.com/awwsmm/rust-mvp">This project</a> is structured as a <a href="https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html">Cargo workspace</a>, where there are multiple crates in a single repo. The idea behind this was that, in a real-life scenario, we would want to publish separate library crates for <code>Actuator</code>s, <code>Sensor</code>s, and so on. If you are a third-party developer creating software for (for example) a smart lightbulb, you might not care about the <code>Sensor</code> library. Your device only has an <em>effect</em> on the environment, it doesn't probe it in any way.</p>
<p>Setting up a project as a Cargo workspace is straightforward, and allows you to pull out "common" code into one or more separate crates, which adheres to the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> principle and just generally makes the whole project easier to develop and maintain.</p>
<h3>Dependencies</h3>
<p>In the interest of keeping the resulting binaries and containers as small as possible, I steered this project away from the big frameworks (<a href="https://github.com/tokio-rs/tokio">tokio</a>, <a href="https://github.com/actix/actix-web">actix</a>, etc.), opting to <a href="https://www.quora.com/Computer-Science-Where-did-the-phrase-Roll-your-own-come-from-and-why-is-it-used-in-CS">"roll our own"</a> solutions wherever we could. Currently, the project has only eight dependencies</p>
<ol>
<li><a href="https://github.com/keepsimple1/mdns-sd"><code>mdns-sd</code></a> for mDNS networking</li>
<li><a href="https://github.com/chronotope/chrono"><code>chrono</code></a> for UTC timestamps and timestamp de/serialization</li>
<li><a href="https://github.com/rust-random/rand"><code>rand</code></a> for random number generation</li>
<li><a href="https://github.com/EstebanBorai/local-ip-address"><code>local-ip-address</code></a> for local IP address discovery</li>
<li><a href="https://github.com/rust-phf/rust-phf"><code>phf</code></a> for compile-time static <code>Map</code>s</li>
<li><a href="https://github.com/rust-lang/log"><code>log</code></a> the <code>rust-lang</code> official logging framework</li>
<li><a href="https://github.com/rust-cli/env_logger"><code>env_logger</code></a> a minimal logging implementation</li>
<li><a href="https://plotly.com/javascript/"><code>plotly</code></a> for graphing data in the Web UI</li>
</ol>
<p>Even some of these are not strictly necessary. We could</p>
<ul>
<li>do away with <code>chrono</code> by rolling our own timestamp de/serialization</li>
<li>remove <code>phf</code> by just creating this single static <code>Map</code> at runtime</li>
<li>do away with <code>log</code> and <code>env_logger</code> by reverting to using <code>println!()</code> everywhere</li>
</ul>
<p><code>mdns-sd</code> and <code>local-ip-address</code> are critical; they ensure the <code>Device</code>s on the network can connect to one another. <code>rand</code> is critical for the <code>Environment</code>, and appears only in that crate's dependencies. <code>plotly</code> is critical to the Web UI, hosted by the <code>Controller</code>, which (as of this writing) shows just a live plot and nothing else.</p>
<p><img src="/blog/what-this-senior-developer-learned-from-his-first-big-rust-project/iot-graph.gif" alt="The live plot in question."></p>
<p>Finally, for containerization of services, we used <a href="https://hub.docker.com/_/rust"><code>rust:alpine</code></a> base image in a <a href="https://docs.docker.com/build/building/multi-stage/">multi-stage build</a>. Only a single dependency needed to be installed in the initial stage, <a href="https://pkgs.alpinelinux.org/package/edge/main/armv7/musl-dev"><code>musl-dev</code></a>, which is required by the <code>local-ip-address</code> crate.</p>
<p>The final sizes of the four binaries produced (for the <code>Controller</code>, <code>Environment</code>, and one implementation each of the <code>Sensor</code> and <code>Actuator</code> interfaces) ranged from <strong>3.6MB</strong> to <strong>4.8MB</strong>, an order of magnitude smaller than the JRE, which clocks in <a href="https://www.oracle.com/java/technologies/downloads/#jre8-linux">around 50-100MB</a>, depending on configuration.</p>
<p>The containers were a bit larger, coming in around <strong>13.5MB</strong> to <strong>13.7MB</strong>. This is still peanuts compared to container image sizes I'm used to for Scala-based projects -- I find that Scala container images are typically in the 100s of MBs range, so &#x3C; 15MB is a breath of fresh air.</p>
<h3>Service Discovery and Messaging</h3>
<p>As <a href="https://github.com/rust-sketches/ping-pong-mdns">this sketch shows</a>, it's actually really straightforward to get two services to discover each other via mDNS with the <a href="https://github.com/keepsimple1/mdns-sd"><code>mdns-sd</code></a> crate. Once services knew about each other, they could communicate.</p>
<p>The easiest way that I know of for two services on a network to communicate with each other is over HTTP. So in this project</p>
<ul>
<li>Service A discovers Service B via mDNS, retrieving its <a href="https://github.com/keepsimple1/mdns-sd/blob/main/src/service_info.rs"><code>ServiceInfo</code></a></li>
<li>Service A opens a <a href="https://doc.rust-lang.org/std/net/struct.TcpStream.html"><code>TcpStream</code></a> by connecting to Service B using the address extracted from its <code>ServiceInfo</code></li>
<li>every service (including Service B) opens a <a href="https://doc.rust-lang.org/std/net/struct.TcpListener.html"><code>TcpListener</code></a> to its own address, listening for incoming TCP connections</li>
<li>Service A sends a <code>Message</code> to Service B via its <code>TcpStream</code>, Service B receives it on its <code>TcpListener</code>, handles it, and sends a response to Service A, closing the socket</li>
</ul>
<p>These <code>Message</code>s don't necessarily need to be HTTP-formatted messages, but it makes it easier to interact with them "from the outside" (via <code>curl</code>) if they are.</p>
<p>Similarly, the data points (called <code>Datum</code>s in this project) sent via HTTP don't <em>need</em> to be serialized to JSON, but they are, because it makes it easier to interact with that data in a browser, or on the command-line.</p>
<p>Construction of HTTP-formatted messages and de/serialization of JSON was all done by hand in this repo, to avoid bringing in unnecessary dependencies.</p>
<blockquote>
<p><strong>TIP:</strong> one "gotcha" I encountered in writing the service discovery code was that each service needs its own mDNS <a href="https://github.com/keepsimple1/mdns-sd/blob/main/src/service_daemon.rs"><code>ServiceDaemon</code></a>. In the original demo, a single daemon was instantiated and <code>clone()</code>d, with the clones passed into each service. But then only the <code>Actuator</code> (or only the <code>Sensor</code>) would see, for example, the <code>Environment</code> come online. It would consume the <a href="https://github.com/keepsimple1/mdns-sd/blob/main/src/service_daemon.rs#L1882"><code>ServiceEvent</code></a> announcing that device's discovery on the network, and the next service wouldn't be able to see it come online. So, heads-up: create a separate daemon for each service which needs to listen to events.</p>
</blockquote>
<h3>Common Patterns and Observations</h3>
<p>With the basic project structure in place, and with the services able to communicate, I noticed a few patterns reoccurring as the project came to life.</p>
<h4><code>Arc&#x3C;Mutex&#x3C;Everything>></code></h4>
<p>In this project, the <code>Device</code>s have some state which is often updated across threads. For instance, the <code>Controller</code> uses one thread to constantly look for new <code>Sensor</code>s and <code>Actuator</code>s on the network, and adds any it finds to its memory.</p>
<p>To safely update data shared across multiple threads, I found myself wrapping lots of things in <code>Arc&#x3C;Mutex&#x3C;...>></code> boxes, following <a href="https://doc.rust-lang.org/book/ch16-03-shared-state.html#atomic-reference-counting-with-arct">this example</a> from <a href="https://doc.rust-lang.org/book/title-page.html">The Book</a>.</p>
<p>I'd be interested in knowing if there's a better / more ergonomic / more idiomatic way of doing this.</p>
<h4>Cloning before <code>move</code>-ing into a new thread</h4>
<p>Another pattern that appears a few times in this repo is something like</p>
<pre><code class="hljs language-rs"><span class="hljs-keyword">fn</span> <span class="hljs-title function_">my_method</span>(&#x26;<span class="hljs-keyword">self</span>) {
    <span class="hljs-keyword">let</span> <span class="hljs-variable">my_field</span> = <span class="hljs-keyword">self</span>.field.<span class="hljs-title function_ invoke__">clone</span>();
    std::thread::<span class="hljs-title function_ invoke__">spawn</span>(<span class="hljs-keyword">move</span> || {
        <span class="hljs-comment">// do something with my_field</span>
    })
}
</code></pre>
<p>We cannot rearrange this to</p>
<pre><code class="hljs language-rs"><span class="hljs-keyword">fn</span> <span class="hljs-title function_">my_method</span>(&#x26;<span class="hljs-keyword">self</span>) {
    std::thread::<span class="hljs-title function_ invoke__">spawn</span>(<span class="hljs-keyword">move</span> || {
        <span class="hljs-keyword">let</span> <span class="hljs-variable">my_field</span> = <span class="hljs-keyword">self</span>.field; <span class="hljs-comment">// will not compile</span>
        <span class="hljs-comment">// do something with my_field</span>
    })
}
</code></pre>
<p>because "<code>Self</code> cannot be shared between threads safely" (<a href="https://doc.rust-lang.org/error_codes/E0277.html">E0277</a>). Similarly, anything wrapped in an <code>Arc&#x3C;...></code> needs to be <code>clone</code>d as well</p>
<pre><code class="hljs language-rs"><span class="hljs-keyword">fn</span> <span class="hljs-title function_">my_other_method</span>(&#x26;<span class="hljs-keyword">self</span>) {
    <span class="hljs-keyword">let</span> <span class="hljs-variable">my_arc</span> = Arc::<span class="hljs-title function_ invoke__">clone</span>(&#x26;<span class="hljs-keyword">self</span>.arc);
    std::thread::<span class="hljs-title function_ invoke__">spawn</span>(<span class="hljs-keyword">move</span> || {
        <span class="hljs-comment">// do something with my_arc</span>
    })
}
</code></pre>
<p>I've ended up with a few <code>thread::spawn</code> sites with big blocks of <code>clone</code>d data just above them.</p>
<p>There's an <a href="https://github.com/rust-lang/rfcs/issues/2407">RFC</a> for this issue, which has been open since 2018. It looks like it's making some progress lately, but it could be a while before we no longer need to manually <code>clone</code> everything that gets <code>move</code>d into a thread.</p>
<h4>It's too easy to <code>.unwrap()</code></h4>
<p>This project is not very large -- it's about 5000 lines of Rust code, by my estimate. But in those 5000 lines, <code>.unwrap()</code> appears over 100 times.</p>
<p>When developing something new, it's easier (and more fun) to focus on the <a href="https://en.wikipedia.org/wiki/Happy_path">"happy path"</a> and leave exception handling for later. Rust makes this pretty easy: assume success, call <code>.unwrap()</code> on your <code>Option</code> or <code>Result</code>, and move on; it's very easy to bypass proper error handling. But it's a pain in the neck to add it in later (imagine adding error handling for all 100+ of those <code>.unwrap()</code> sites).</p>
<p>It would be better, in my opinion, to keep on top of these <code>.unwrap()</code>s <em>as they appear</em>.</p>
<p>Near the end of this MVP, as I counted all of these sites with missing error handling, I found myself longing for a <a href="https://github.com/rust-lang/rust-clippy"><code>clippy</code></a> rule which would disallow any <code>.unwrap()</code>...</p>
<p>As it turns out, <a href="https://github.com/rust-lang/rust-clippy/issues/9612">there already are</a> <code>unwrap_used</code> and <code>expect_used</code> lints which can be used to error out if either of these methods are called. I will definitely be enabling these lints on my personal projects in the future, and I hope that they will eventually become the default.</p>
<h4>Parsing</h4>
<p>I wrote a lot of custom parsing code.</p>
<p>A common pattern I followed was to <code>impl Display</code> for some type, then add a <code>pub fn parse()</code> method to turn the serialized version back into the appropriate type.</p>
<p>This is probably not the best way to do this -- user-friendly strings for display are different things from compact serialized representations for message passing and persistence. If I were to do this again, I would probably use a crate like <a href="https://github.com/serde-rs/serde"><code>serde</code></a> for de/serialization, and save <code>impl Display</code> for a user-friendly string representation.</p>
<p>In addition, I "rolled my own" routing. When an HTTP request was found on a <code>TcpStream</code>, I would manually check the <code>start_line</code> (something like <code>POST /command HTTP/1.1</code>) to route to the appropriate endpoint. In the future, I might leave this to an external crate... maybe something like <a href="https://github.com/hyperium/hyper"><code>hyper</code></a>.</p>
<h4><code>pub struct</code>s should implement <code>PartialEq</code> when possible</h4>
<p>I think this is probably a good rule of thumb for any <code>pub</code> data type: implement <code>PartialEq</code> when appropriate, so consumers of your crate can test for equality. The <code>ServiceInfo</code> type in <code>mdns-sd</code> does not <code>derive</code> <code>PartialEq</code>. This means I couldn't easily test for equality of two <code>ServiceInfo</code>s in tests.</p>
<p>In lieu of this, I checked that every <code>pub</code> method on two instances returned the same values. This was kind of a pain, resulting in big blocks of</p>
<pre><code class="hljs language-rs"><span class="hljs-built_in">assert_eq!</span>(actual.<span class="hljs-title function_ invoke__">foo</span>(), expected.<span class="hljs-title function_ invoke__">foo</span>());
<span class="hljs-built_in">assert_eq!</span>(actual.<span class="hljs-title function_ invoke__">bar</span>(), expected.<span class="hljs-title function_ invoke__">bar</span>());
<span class="hljs-built_in">assert_eq!</span>(actual.<span class="hljs-title function_ invoke__">baz</span>(), expected.<span class="hljs-title function_ invoke__">baz</span>());
<span class="hljs-comment">// ...</span>
</code></pre>
<p>It would have been nice to just write</p>
<pre><code class="hljs language-rs"><span class="hljs-built_in">assert_eq!</span>(actual, expected)
</code></pre>
<p>instead.</p>
<h4><code>trait</code>s implementing other <code>trait</code>s can get messy, fast</h4>
<p>In this project, there's a <code>trait Device</code> with an abstract method called <code>get_handler()</code></p>
<pre><code class="hljs language-rs"><span class="hljs-comment">// examples in this section are abridged for clarity</span>
<span class="hljs-keyword">pub</span> <span class="hljs-keyword">trait</span> <span class="hljs-title class_">Device</span> {
    <span class="hljs-keyword">fn</span> <span class="hljs-title function_">get_handler</span>(&#x26;<span class="hljs-keyword">self</span>) <span class="hljs-punctuation">-></span> Handler;
}
</code></pre>
<p>The <code>Sensor</code> and <code>Actuator</code> <code>trait</code>s both implement <code>Device</code>, and provide default implementations of <code>get_handler()</code></p>
<pre><code class="hljs language-rs"><span class="hljs-keyword">pub</span> <span class="hljs-keyword">trait</span> <span class="hljs-title class_">Sensor</span>: Device {
    <span class="hljs-keyword">fn</span> <span class="hljs-title function_">get_handler</span>(&#x26;<span class="hljs-keyword">self</span>) <span class="hljs-punctuation">-></span> Handler {
        <span class="hljs-comment">// some default implementation here for all `Sensor`s</span>
    }
}
</code></pre>
<pre><code class="hljs language-rs"><span class="hljs-keyword">pub</span> <span class="hljs-keyword">trait</span> <span class="hljs-title class_">Actuator</span>: Device {
    <span class="hljs-keyword">fn</span> <span class="hljs-title function_">get_handler</span>(&#x26;<span class="hljs-keyword">self</span>) <span class="hljs-punctuation">-></span> Handler {
        <span class="hljs-comment">// some default implementation here for all `Actuator`s</span>
    }
}
</code></pre>
<p>But then there are the concrete implementations of <code>Sensor</code> and <code>Actuator</code></p>
<pre><code class="hljs language-rs"><span class="hljs-keyword">pub</span> <span class="hljs-keyword">struct</span> <span class="hljs-title class_">TemperatureSensor</span> {
  <span class="hljs-comment">// ...</span>
}

<span class="hljs-keyword">impl</span> <span class="hljs-title class_">Sensor</span> <span class="hljs-keyword">for</span> <span class="hljs-title class_">TemperatureSensor</span> {}

<span class="hljs-keyword">impl</span> <span class="hljs-title class_">Device</span> <span class="hljs-keyword">for</span> <span class="hljs-title class_">TemperatureSensor</span> {
    <span class="hljs-keyword">fn</span> <span class="hljs-title function_">get_handler</span>(&#x26;<span class="hljs-keyword">self</span>) <span class="hljs-punctuation">-></span> Handler {
        Sensor::<span class="hljs-title function_ invoke__">get_handler</span>(<span class="hljs-keyword">self</span>)
    }
}
</code></pre>
<pre><code class="hljs language-rs"><span class="hljs-keyword">pub</span> <span class="hljs-keyword">struct</span> <span class="hljs-title class_">TemperatureActuator</span> {
  <span class="hljs-comment">// ...</span>
}

<span class="hljs-keyword">impl</span> <span class="hljs-title class_">Actuator</span> <span class="hljs-keyword">for</span> <span class="hljs-title class_">TemperatureActuator</span> {}

<span class="hljs-keyword">impl</span> <span class="hljs-title class_">Device</span> <span class="hljs-keyword">for</span> <span class="hljs-title class_">TemperatureActuator</span> {
    <span class="hljs-keyword">fn</span> <span class="hljs-title function_">get_handler</span>(&#x26;<span class="hljs-keyword">self</span>) <span class="hljs-punctuation">-></span> Handler {
        Actuator::<span class="hljs-title function_ invoke__">get_handler</span>(<span class="hljs-keyword">self</span>)
    }
}
</code></pre>
<p>There already is a concrete implementation of <code>get_handler()</code> in <code>Sensor</code> / <code>Actuator</code>, so we don't actually need anything in the <code>impl Sensor</code> / <code>impl Actuator</code> blocks (unless there are other abstract methods), but we <em>do</em> need this awkward <code>impl Device</code> in each case.</p>
<p>As far as <code>Device</code> "knows", <code>TemperatureActuator</code> hasn't implemented its abstract method. But <em>we</em> know that <code>Actuator</code> has, and that <code>TemperatureActuator</code> implements <code>Actuator</code>. There seems to be some information missing here that the compiler could fill in, theoretically, but currently isn't.</p>
<h4>Rust could use a more robust <code>.join()</code> method on slices</h4>
<p>Other languages let you specify a <code>start</code> and <code>end</code> parameter when joining an array of strings, so you could easily do something like</p>
<pre><code class="hljs language-rs">[<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>].<span class="hljs-title function_ invoke__">join</span>(<span class="hljs-string">"My favourite fruits are: "</span>, <span class="hljs-string">", "</span>, <span class="hljs-string">". How about yours?"</span>)
<span class="hljs-comment">//                                 |--------- start ---------| |sep|  |------- end -------|</span>
</code></pre>
<p>which would result in a string like <code>"My favourite fruits are: apple, banana, cherry. How about yours?"</code>, but Rust doesn't yet have this functionality.  This would be a great little quality-of-life addition to the slice primitive type.</p>
<h4>All of my <code>Result</code> error types are <code>String</code>s</h4>
<p>This is certainly the easiest way to quickly build something while mostly ignoring failures, but at some point, I should go back and replace these with proper error types. Clients should be able to match on the type of the error, rather than having to parse the message, to figure out what failed.</p>
<p>Any <code>Result</code> types which leak to the external world (to clients) should probably have proper <code>Err</code> variants, and not just <code>String</code> messages. This is another thing I wish <code>clippy</code> had a lint for: no <code>&#x26;str</code> or <code>String</code> <code>Err</code> types.</p>
<h4><code>S: Into&#x3C;String></code> instead of <code>&#x26;str</code></h4>
<p>Rust will <a href="https://doc.rust-lang.org/book/ch08-02-strings.html#concatenation-with-the--operator-or-the-format-macro">automatically coerce <code>&#x26;String</code>s to <code>&#x26;str</code>s</a>, and so the traditional wisdom is that function arguments should be of type <code>&#x26;str</code>, so the user doesn't need to construct a new <code>String</code> to pass to a function which takes a string argument. If you already have a <code>String</code>, you can just call <code>as_ref()</code> on it to get a <code>&#x26;str</code>.</p>
<p>But Rust will only do a single implicit coercion at a time. So we can't convert some type <code>T: Into&#x3C;String></code> into a <code>String</code> <em>and then</em> into a <code>&#x26;str</code>. This is why I opted for <code>S: Into&#x3C;String></code> instead of <code>&#x26;str</code> arguments in a few places. <code>&#x26;str</code> implements <code>Into&#x3C;String></code> and so does any type which implements <code>Into&#x3C;String></code> (or <code>Display</code>).</p>
<p>It is definitely less performant, since we're copying data on the heap, but also a bit more ergonomic, since we don't need to pass <code>t.to_string().as_ref()</code> (when <code>t: T</code> and <code>T: Into&#x3C;String></code>) to the function, but just <code>t</code> itself.</p>
<p>Apparently I'm not the first person to discover this pattern, either: <a href="https://github.com/search?q=%3A+Into%3CString%3E+language%3ARust&#x26;type=code&#x26;l=Rust"><code>Into&#x3C;String></code> returns 176,000 hits on GitHub</a>.</p>
<p><a name="conclusion"></a></p>
<h2>Conclusion</h2>
<p>I learned a lot in building this project: about mDNS networking, the nitty-gritty of HTTP message formats, and writing bigger projects in Rust. To summarize the points I raised above...</p>
<p>Things I know I need to do better</p>
<ul>
<li>I shouldn't be using <code>Display</code> for serialization. In the future, I will look into using a crate like <a href="https://github.com/serde-rs/serde"><code>serde</code></a> instead.</li>
<li>I shouldn't be using <code>String</code> for all of my <code>Err</code> variants. Clients of the library crates I'm producing should be able to handle an error without having to parse a string message. In the future, I will build error <code>enum</code>s as soon as I start producing errors.</li>
</ul>
<p>Things I'm looking forward to from the Rust community</p>
<ul>
<li>Explicit <code>clone</code>-ing prior to a <code>move</code> closure is a pain. I'm following <a href="https://github.com/rust-lang/rfcs/issues/2407">this GitHub issue</a> in hopes that this becomes more ergonomic in the future.</li>
<li>A <code>clippy</code> error for <code>String</code> / <code>&#x26;str</code> <code>Err</code> variants would be nice, as well.</li>
<li>Rust could use a more robust <code>.join()</code> method on string slices, with <code>start</code> and <code>end</code> parameters. As far as I can tell, this issue is not yet being tracked. After this article is published, I hope to open an RFC for this small feature.</li>
<li>I'm hoping that eventually the compiler will be smart enough to know that when <code>B: A</code> and <code>C: B</code>, where <code>A</code> defines some abstract method and <code>B</code> implements that abstract method, that <code>c: C</code> already has that method implemented, without having to explicitly tell the compiler about that implementation. But that might be a ways off.</li>
</ul>
<p>Things I still have questions about</p>
<ul>
<li>Is <code>Arc&#x3C;Mutex&#x3C;Everything>></code> really the best way to mutate data across multiple threads? Or is there a more idiomatic (or safer) way of doing this?</li>
</ul>
<p>Things I would recommend to other Rust developers</p>
<ul>
<li>Please <code>impl</code> <code>PartialEq</code> on any <code>pub</code> data type published by your crate, whenever possible. Your clients will thank you (hopefully).</li>
<li>Don't be afraid to use <code>S: Into&#x3C;String></code> instead of <code>&#x26;str</code>. It might be less performant, but it's also more ergonomic, and you're definitely not the first person to do it.</li>
<li>Enable <code>clippy</code>'s <code>unwrap_used</code> and <code>expect_used</code> lints, to force yourself to tackle error scenarios head-on, instead of pushing them aside to deal with them later.</li>
</ul>
<hr>
<p>If you've made it this far... thanks for reading!</p>
<p>Please direct any feedback you may have about the above article to the email address on <a href="https://www.awwsmm.com/CV_Watson.pdf">my CV</a>. This was a fantastic learning experience and I'm excited to do some more serious Rust development in the near future.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[Software Development is About Compromise]]></title>
            <link>https://awwsmm.com/blog/software-development-is-about-compromise</link>
            <guid isPermaLink="false">software-development-is-about-compromise</guid>
            <pubDate>Sun, 09 Apr 2023 00:00:00 GMT</pubDate>
            <description><![CDATA[A Case Study in Building a Website using Next.js]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><h2>Trade-Offs in Software Development</h2>
<blockquote>
<p>"Where's all my CPU and memory gone?"</p>
<p>-- <a href="https://news.ycombinator.com/item?id=14868999">thegeomaster</a></p>
</blockquote>
<h3>Software development is -- and has always been -- about trade-offs.</h3>
<p>The <a href="https://en.wikipedia.org/wiki/CAP_theorem">CAP theorem</a> tells us that we need to choose between consistency, availability, and partition tolerance when designing distributed data stores.</p>
<p><a href="https://www.indeed.com/career-advice/career-development/cache-pros-and-cons">Caches</a> can make information available more quickly, but it might be out of date, and it will definitely use more storage space than making a fresh request each time.</p>
<p>And, as always, money can be a factor. <a href="https://reviewed.usatoday.com/laptops/features/ssd-vs-hdd">SSDs are faster than HDDs</a>, but they are more expensive per GB. And microservices in a distributed system should each have their own database, but cloud computing costs can mean that shared DBs are more cost-effective.</p>
<p>Weighing the pros and cons of varied solutions to a problem was something I needed to tackle recently when redesigning part of my personal website, <a href="https://awwsmm.com">awwsmm.com</a>. Here's how that went down...</p>
<h2>A Case Study: My Website</h2>
<h3>The Setup</h3>
<p>My website is a pretty minimal Next.js site, written in TypeScript, hosted <a href="https://github.com/awwsmm/awwsmm.com">on GitHub</a>, built and deployed <a href="https://vercel.com/">by Vercel</a>.</p>
<p>In general, Next.js allows you to have two kinds of pages: static pre-rendered pages, and dynamic pages, rendered "just in time", when a visitor to your website tries to visit that page.</p>
<p>My website has static <a href="https://www.awwsmm.com/blog">blog posts</a>, as well as <a href="https://www.awwsmm.com/projects">"project" pages</a>, which give a quick overview of personal projects that I've been working on lately.</p>
<p>My initial design was for a given project page (for example, <a href="https://www.awwsmm.com/projects/awwsmm.com">this one for my website itself</a>) to have an up-to-date commit history, interleaved with occasional "log entries", summarizing big sweeping changes made to these projects. (Kind of like release notes, but with more detail behind <em>why</em> certain changes are being made.)</p>
<p>So what was the problem?</p>
<h3>The Problem</h3>
<p>The problem was that these project pages were statically rendered; they were built in advance.</p>
<p>I would <a href="https://github.com/awwsmm/awwsmm.com/blob/cfec0c66a0cf1ba8cc54459ee77c85b707d21d61/lib/utils/ProjectUtils.ts#L59">request the commit history of a project from GitHub</a> and write it to a local cache, saved in the repository.</p>
<p>When <a href="https://github.com/awwsmm/awwsmm.com/pull/74">a new PR is opened</a> against the repo containing my website, Vercel runs a test deployment. When the test deployment looks good, I hit "merge" and the new changes are added to the repo in a merge commit.</p>
<p>But, because the cache is created only when I'm developing locally, <em>this merge commit is not a part of the commit history in the cache.</em> It couldn't possibly be. It would require updating the cache file, which would introduce changes not included in that commit, which would require another commit, ad infinitum.</p>
<p>This means that the commit history for the <code>awwsmm.com</code> project page is <em>always</em> at least one commit behind <code>master</code>.</p>
<p>This bothered me, and I wanted to see if I could fix it.</p>
<h3>First Attempt: Environment-Aware Caching</h3>
<p><a href="https://github.com/awwsmm/awwsmm.com/commit/569a6368f7bd115a13aa219b398b4bf23eab04ad#diff-e1998422d9b0a8903593c437a2bf074f2d47e10bede05c333e3a2312797ca486">My first attempt at a solution</a> was (what I'm going to call) "environment-aware caching".</p>
<p>What if, after the deployment passed and the new PR was merged into <code>master</code>, Vercel ignored the cache, only using it as a backup? During deployment, we could hit the GitHub API again, which should then have the new commit, right?</p>
<p>This required knowing which environment the build was running on. This is straightforward, as Vercel populates <a href="https://vercel.com/docs/concepts/projects/environment-variables/system-environment-variables">a <code>VERCEL_ENV</code> environment variable</a> to <code>"production"</code>, <code>"preview"</code>, or <code>"deployment"</code>, depending on where the build is running.</p>
<p>But this also required maintaining a cache which we hopefully would never fall back to, which seemed kind of silly.</p>
<p>It also meant that each release would have to be deployed at least twice: once to satisfy the checks before merging the PR, and once after the PR was merged to pick up the new commit on <code>master</code>. I'd have to remember to do this "double deployment" to keep things up-to-date.</p>
<p>Finally, there was some human error here in that I tried to use <a href="https://github.com/awwsmm/awwsmm.com/commit/cb38f6411859de4586f945eaae6231ebcd87a78f#diff-8779cf4bd89603a2f8a50f4ea24460afbd79e6d8b65ba8575183d02f47cf074b">the same caching mechanism for "last updated" dates on my blog posts</a>, confusing the issue.</p>
<p>All in all, this solution was pretty complex to maintain (all I want is a static blog), and it put me off of keeping my website up-to-date for a while. When I finally came back here after a few months, I decided that a simpler solution was in order.</p>
<h3>Second Attempt: Server-Side Rendering</h3>
<p>So how about trying to <a href="https://github.com/awwsmm/awwsmm.com/commit/5daf1b29cbdcafa7f26f6fed340adbfc6482df2e#diff-dc938814c5900cd48c67f3c5b743ac02c3d0730245e9fa633d02e9fef4cdb801R104">render the project pages "just in time"?</a></p>
<p>Vercel's <a href="https://vercel.com/blog/nextjs-server-side-rendering-vs-static-generation">server-side rendering (SSR)</a> also generates static pages, but it renders them only when the user navigates to the page, not during deployment.</p>
<p>"This is great!" I thought. I could just request the commit history when the page is requested, and it would always be up-to-date.</p>
<p>Unfortunately, requesting and processing 100 commits from GitHub seemed to be too much to ask. I was consistently waiting about 3 seconds for the page to load, which is <a href="https://web.dev/ttfb/">really bad</a>. Project pages with shorter commit histories loaded a bit faster, but there was still a noticeable delay. Sending the request to GitHub, awaiting a response, processing the response, generating the resulting page, and displaying it just took too much time.</p>
<p>This approach would also send a request to GitHub <em>every time</em> a user loaded that page.</p>
<p>This second issue could be solved by <a href="https://github.com/awwsmm/awwsmm.com/commit/d6eb611eb5d9c746670cceeffc0fecfe32fd0817#diff-dc938814c5900cd48c67f3c5b743ac02c3d0730245e9fa633d02e9fef4cdb801R105-R123">fine-tuning the <code>Cache-Control</code></a> header sent along with the request, such that I could guarantee that the 5000-requests-per-hour (authenticated) limit would never be exceeded.</p>
<p>But the first issue remained a problem.</p>
<h3>Third Attempt: Non-Blocking Server-Side Rendering</h3>
<p>"Maybe I'm the problem" I thought.</p>
<p>"Maybe it's the way I (think I) am blocking inside of <code>getServerSideProps</code>."</p>
<p><a href="https://github.com/awwsmm/awwsmm.com/commit/ea8ec00ed8905f55d6bb780df5535dcb459af638">I rearranged this method</a> to not <code>await</code> anywhere, but return a <code>Promise</code> which is a result of other <code>Promise</code>s chained together with <code>then</code>, and nothing else.</p>
<p>I was hoping that, with everything done in a non-blocking way in the return value, Vercel could work some magic to speed up the call. (Maybe it could run the request as soon as the user <em>hovered over</em> the link to the page?)</p>
<p>But it didn't help. I was still stuck at ~3 seconds of loading time. Worth a try, at least.</p>
<h3>Fourth Attempt: GraphQL</h3>
<p>"Maybe the response from GitHub is taking so long because it's returning too much data?"</p>
<p>I wasn't using <em>most</em> of the response anyway; all I cared about was the commit hash, the message, and the date. I'd never used GraphQL before, but I knew that it could be used in situations like this, where you wanted to request only <em>particular</em> data from an endpoint.</p>
<p>So I learned enough about GraphQL and GitHub's API to <a href="https://github.com/awwsmm/awwsmm.com/commit/f6260bbc9bd1d181fbf3f613a73008f1cfe53e4c#diff-93b7ed2c3a46038993bf9d2c1478cc9dbb3f14e3beeafd30cb21983fbfc75befR67-R79">request only the commit data I cared about</a>.</p>
<p>This sped up the page a bit <em>locally</em> but not in production on Vercel. It was still taking about 3 seconds.</p>
<h3>Fifth Attempt: Timeout / Fallback to Cache</h3>
<p>"Well, if it's loading fast enough locally, but not remotely, maybe I can set a timeout threshold?"</p>
<p>My thought was that I could <a href="https://www.google.com/search?q=time+is+a+flat+circle">cache</a> a "stale" version of the page to display if the "live" version of the page took too long to load. Maybe longer than 500ms or so.</p>
<p>So I would now <a href="https://github.com/awwsmm/awwsmm.com/commit/927db29fb8cdfb53402d8a7aeff047503ec36ff1#diff-93b7ed2c3a46038993bf9d2c1478cc9dbb3f14e3beeafd30cb21983fbfc75bef">generate a cache when building locally</a>, and save the cache to the repo. In production, I would attempt to request fresh data from GitHub, but if it took longer than 500ms, I would fall back to the cache.</p>
<p>...but it still took 3 seconds to render the page remotely.</p>
<p>"Why?" I thought, pulling my hair out in frustration.</p>
<p>Other project pages loaded quickly... maybe Vercel was just (somwehow?) slow to process this 600-line JSON file, generate the hundreds of components for it, style all of them, and display them.</p>
<p>I found <a href="https://github.com/vercel/vercel/discussions/7961">issues on the <code>vercel</code> repo</a> of people complaining about similar problems. Maybe it just took a few seconds for Vercel to spin up a runner to render the page? (That didn't seem to square with the load times of the other project pages.)</p>
<p>I took solace in the fact that other people on the Internet <em>also</em> thought that <a href="https://www.youtube.com/watch?v=1er7Zqs_h9k"><code>getServerSideProps</code> is weird</a> and unintuitive.</p>
<p>I assessed other possible avenues for investigation: <a href="https://web.dev/custom-metrics/?utm_source=devtools#server-timing-api">timing the response?</a>, <a href="https://vercel.com/blog/nextjs-server-side-rendering-vs-static-generation">actually reading the docs? (no thanks)</a>, incremental static generation?, <a href="https://vercel.com/docs/concepts/functions/edge-functions">edge functions?</a>.</p>
<p>I was beginning to lose the will to live... all I wanted was a blog.</p>
<h2>Regrouping</h2>
<p>I took a breather and came back to it all after a little while.</p>
<p>"What is it I actually want?"</p>
<ul>
<li>up-to-date commit histories</li>
<li>fast page loads</li>
</ul>
<p>The problem was that those two things were -- if not mutually exclusive, at least -- in competition with each other. Up-to-the-second commit histories would require a request to GitHub as soon as the user requested the project page. Which meant that all of the data fetching, and processing, and rendering would have to be done <em>quickly</em>.</p>
<p>This didn't seem like too big of an ask to me, but apparently it was. Maybe it was my code, maybe it was the Lambda cold start times, maybe it was something on Vercel's end... whatever it was, it was pinning me to 3-second page load times.</p>
<p>"Maybe I can request and process <em>most</em> of the history in advance, then only request <em>recent</em> history when a user clicks on a page?"</p>
<p>This sounded overcomplicated, though. (Unlikely, but) what if a project had had 100 new commits since I last deployed my website (and generated the cache)? Then I would have the same problem: trying to request and render 100 commits onto this history page.</p>
<p><a href="https://github.com/awwsmm/awwsmm.com/commit/34ee82581280b28da6041b4966da0d423665b885">So I compromised</a>, and came up with a simpler solution:</p>
<ol>
<li>
<p>generate <code>project/</code> pages statically</p>
<p>This solves the load time issue -- by the time we get to production, the pages will have already been generated, so nothing needs to be done except displaying them.</p>
<p>But this means that we will not have an up-to-date commit history.</p>
</li>
<li>
<p>accept that the commit history will not be up-to-date</p>
<p>I'd already sunk so much time into this, I was ready to compromise.</p>
<p>Nobody coming to my website will care if my commit histories are slightly out of date. So I decided to just put a disclaimer at the top and bottom of the histories, saying something like "for the most up-to-date commit history, see GitHub".</p>
</li>
</ol>
<p>Now, we can generate pages in advance, keep load times to basically zero, and we don't have to worry about complex caching solutions, or what environment the build is running in, or GitHub rate limits, or anything.</p>
<p>My compromise was that my time and energy were worth more to me than having this one feature on my website be exactly the way I had envisioned it initially.</p>
<h2>Software Development is About Compromise</h2>
<p>In my case, I tried and tried to get my website to do what I wanted it to, but my two requirements: up-to-date commit histories and fast loading times, were in direct competition with each other.</p>
<p>Having an up-to-date history will require a request when the user clicks the button, and processing the result of that request, which will take time.</p>
<p>Surely there are more complex solutions which balance these two better, but in the end, having these pages be up-to-date is not critical for my blog. Choosing where to use my time is another trade-off. I learned a lot about Vercel, GraphQL, and Promises in JavaScript / TypeScript during this process, but ultimately, "see GitHub" is good enough for me. And that's a compromise I'm willing to accept.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[Elegant Multi-Line Shell Strings]]></title>
            <link>https://awwsmm.com/blog/elegant-multi-line-shell-strings</link>
            <guid isPermaLink="false">elegant-multi-line-shell-strings</guid>
            <pubDate>Thu, 17 Mar 2022 00:00:00 GMT</pubDate>
            <description><![CDATA[Ergonomic Multi-Line Strings for bash, zsh, and Other Shells]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><h2>The State of Multi-Line Strings</h2>
<p>Multi-line strings in shells are a pain.</p>
<p>Suppose you want to create a file, using a shell script, which contains the following content</p>
<pre><code class="hljs language-ts">export default class Greeter {
  greet(name: string) { return 'Hello, ' + name + '!'; }
}
</code></pre>
<p>How can this be achieved?</p>
<h3>Some Methods</h3>
<h4>Method 1: a multi-line variable</h4>
<p>This simple solution works when the variable definition is not indented at all</p>
<pre><code class="hljs language-sh">var="export default class Greeter {
  greet(name: string) { return 'Hello, ' + name + '!'; }
}"
</code></pre>
<pre><code>$ echo $var
export default class Greeter {
  greet(name: string) { return 'Hello, ' + name + '!'; }
}
</code></pre>
<p>But what if we're defining <code>$var</code> within a function, and we want it indented along with the rest of the function body?</p>
<pre><code class="hljs language-sh">function my_function() {
  var="export default class Greeter {
    greet(name: string) { return 'Hello, ' + name + '!'; }
  }"
  echo $var
}
</code></pre>
<pre><code class="hljs language-sh">$ my_function
export default class Greeter {
    greet(name: string) { return 'Hello, ' + name + '!'; }
  }
</code></pre>
<p>Oh, well, that's obviously not what we want.</p>
<p>So, simple variable assignment: it works in a very limited subset of cases, when the variable definition is not indented at all. Let's try another method.</p>
<h4>Method 2: a single-line variable with '<code>\n</code>'s for line breaks</h4>
<p>In this method, we replace all of the line breaks in the multiline string with <code>\n</code> line break characters:</p>
<pre><code class="hljs language-sh">function my_function() {
  var="export default class Greeter {\n  greet(name: string) { return 'Hello, ' + name + '!'; }\n}"
  echo $var
}
</code></pre>
<pre><code class="hljs language-sh">$ my_function
export default class Greeter {
  greet(name: string) { return 'Hello, ' + name + '!'; }
}
</code></pre>
<p>The result looks good, but the method is messy. What if we want to reformat this like</p>
<pre><code class="hljs language-ts">export default class Greeter {
  greet(name: string) {
    return 'Hello, ' + name + '!';
  }
}
</code></pre>
<p>That would involve adding more <code>\n</code> characters, and spaces to match the indentation. It's not extremely straightforward:</p>
<pre><code class="hljs language-sh">function my_function() {
  var="export default class Greeter {\n  greet(name: string) {\n    return 'Hello, ' + name + '!';\n  }\n}"
  echo $var
}
</code></pre>
<p>So, explicit line break characters: this works if the text you want formatted won't change often, and if the readability of the implementation doesn't matter. If you want the text-generating code itself to be readable or maintainable, this is not a great solution.</p>
<p>So what else can we do?</p>
<h4>Method 3: Heredocs</h4>
<p>Multiline strings are what <a href="https://en.wikipedia.org/wiki/Here_document">Heredocs</a> were made for:</p>
<blockquote>
<p>In computing, a here document (here-document, here-text, heredoc, hereis, here-string or here-script) is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file. The term is also used for a form of multiline string literals that use similar syntax, preserving line breaks and other whitespace (including indentation) in the text.</p>
</blockquote>
<p>So let's see how well they work for our problem</p>
<pre><code class="hljs language-sh">function my_function() {
  var=$(cat &#x3C;&#x3C;EOF
  export default class Greeter {
    greet(name: string) { return 'Hello, ' + name + '!'; }
  }
  EOF)
  echo $var
}
</code></pre>
<pre><code class="hljs language-sh">$ my_function
/Users/andrew/test.sh:8: parse error near `var=$(cat &#x3C;&#x3C;EOF'
</code></pre>
<p>Oh, uh, yeah, obviously the delimiter sequence (<code>EOF</code> in this case), cannot be indented, and must appear on a line by itself, so we have to write</p>
<pre><code class="hljs language-sh">function my_function() {
  var=$(cat &#x3C;&#x3C;EOF
  export default class Greeter {
    greet(name: string) { return 'Hello, ' + name + '!'; }
  }
EOF
  )
  echo $var
}
</code></pre>
<p>...which is fine, but sort of breaks indentation of the rest of the function body. It also doesn't work:</p>
<pre><code class="hljs language-sh">$ my_function
  export default class Greeter {
    greet(name: string) { return 'Hello, ' + name + '!'; }
  }
</code></pre>
<p>Just like Method #1, this method adds to the output the whitespace we used to indent the function body, which we don't want.</p>
<p>So how can we preserve <em>only</em> the indentation <em>we want</em> (and maybe get rid of that ugly heredoc delimiter)?</p>
<h3>My Method</h3>
<p>Here's how I do it</p>
<pre><code class="hljs language-sh">function my_function() {
  var="$(sed -e 's/^[ ]*\| //g' -e '1d;$d' &#x3C;&#x3C;'--------------------'
    | 
    | export default class Greeter {
    |   greet(name: string) { return `Hello, ${name}!`; }
    | }
    | 
--------------------
    )"
  echo $var
}
</code></pre>
<p>I use pipe characters <code>|</code> to define a "margin", which I then strip out using <code>sed</code>. <code>sed -e 's/^[ ]*\| //g'</code> will remove any number of space characters (<code>[ ]*</code>) at the beginning of the line (<code>^</code>), followed by a pipe (<code>|</code>), followed by one space character (<code>[ ]</code>).</p>
<blockquote>
<p>This "margin" method was inspired by <a href="https://www.oreilly.com/library/view/scala-cookbook/9781449340292/ch01s03.html">Scala's <code>String#stripMargin</code> functionality</a>, which behaves in a very similar way.</p>
</blockquote>
<p>The second <code>sed</code> expression, <code>-e '1d;$d'</code>, removes the first and last line. I add blank lines to provide a bit of visual whitespace around the content I want to write to the variable. If you don't want one or both of these blank lines, remove them with this slight variation on my method</p>
<pre><code class="hljs language-sh">function my_function() {
  var="$(sed -e 's/^[ ]*\| //g' &#x3C;&#x3C;'--------------------'
    | export default class Greeter {
    |   greet(name: string) { return `Hello, ${name}!`; }
    | }
--------------------
    )"
  echo $var
}
</code></pre>
<p>I don't mind the line of hyphens, either, as the <code>EOF</code> replacement, because it sort of acts like the top and bottom margin of the content. But, if you put the heredoc delimiter in quotes, as I have above, you can also include whitespace in it. So you could do something like</p>
<pre><code class="hljs language-sh">function my_function() {
  var="$(sed -e 's/^[ ]*\| //g' &#x3C;&#x3C;'    +'
    | export default class Greeter {
    |   greet(name: string) { return `Hello, ${name}!`; }
    | }
    +
    )"
  echo $var
}
</code></pre>
<p>Though I personally think this leaves a bit too much whitespace under the content. Also, many syntax highlighting algorithms have trouble with this.</p>
<p>With any of these variations, you can indent the content to whatever level you like</p>
<pre><code class="hljs language-sh">function my_function_1() {
  var="$(sed -e 's/^[ ]*\| //g' &#x3C;&#x3C;'--------------------'
    | export default class Greeter {
    |   greet(name: string) { return `Hello, ${name}!`; }
    | }
--------------------
    )"
  echo $var
}

function my_function_2() {
  var="$(sed -e 's/^[ ]*\| //g' &#x3C;&#x3C;'--------------------'
| export default class Greeter {
|   greet(name: string) { return `Hello, ${name}!`; }
| }
--------------------
    )"
  echo $var
}

function my_function_3() {
  var="$(sed -e 's/^[ ]*\| //g' &#x3C;&#x3C;'--------------------'
              | export default class Greeter {
              |   greet(name: string) { return `Hello, ${name}!`; }
              | }
--------------------
    )"
  echo $var
}
</code></pre>
<pre><code class="hljs language-sh">$ my_function_1; my_function_2; my_function_3
export default class Greeter {
  greet(name: string) { return `Hello, ${name}!`; }
}
export default class Greeter {
  greet(name: string) { return `Hello, ${name}!`; }
}
export default class Greeter {
  greet(name: string) { return `Hello, ${name}!`; }
}
</code></pre>
<p>The flexibility -- combined with the visual aesthetics -- of this method is why it's recently become my go-to for multi-line strings in the shell.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[What's Wrong This Time? Part III: The Deep End]]></title>
            <link>https://awwsmm.com/blog/whats-wrong-this-time-part-3</link>
            <guid isPermaLink="false">whats-wrong-this-time-part-3</guid>
            <pubDate>Sun, 06 Mar 2022 00:00:00 GMT</pubDate>
            <description><![CDATA[Debugging a New Feature in a Vercel TypeScript GitHub Repo]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><p><strong>Part III: The Deep End</strong></p>
<p>At this point, I wasn't sure where to go next.</p>
<p>Why should <a href="https://www.awwsmm.com/blog/whats-wrong-this-time-part-2">these blog posts now have a seemingly random publication date</a>, which was not the current date, and was not the date they were first added to the repo? What was going on?</p>
<p>So I did what most programmers do in a situation like this: I added some <code>console.log()</code>s.</p>
<h2>Digging Deeper</h2>
<p>I wanted to know what commits were available, and what information they had. In other words, I wanted better <a href="https://dzone.com/articles/rethinking-programming-automated-observability"><em>observability</em></a> into what was going on in this bit of the codebase.</p>
<p>My first idea was to just <a href="https://github.com/awwsmm/awwsmm.com/commit/a43bf7c356aa4b649ddfbf26528a454ae94bd807">print out the dates of every line returned from <code>git log</code></a>. The output of that (for a given blog post) looked something like</p>
<pre><code>lines returned from git log
2022-01-09T20:48:23+00:00
2022-01-06T09:18:41+00:00
</code></pre>
<p>...okay, not extremely useful. Why are there only two commits here? This is just the same information we had on the website. Maybe <a href="https://github.com/awwsmm/awwsmm.com/commit/0477f384c0cb604c8cd4b64307c1b37b150575dc">printing out the hash of each commit</a> would be a bit more helpful? Then I could check if there was anything unusual about these commits</p>
<pre><code>lines returned from git log
69e038a919e448251fa2211a9fcf3fda914812fe @ 2022-01-09T20:48:23+00:00
d5cf8fbc05891ac9d8d7067b5cb1fb195dc2cf99 @ 2022-01-06T09:18:41+00:00
</code></pre>
<p>Now we can search GitHub for that commit <a href="https://github.com/awwsmm/awwsmm.com/commit/d5cf8fbc05891ac9d8d7067b5cb1fb195dc2cf99"><code>dc2cf99</code></a>.</p>
<p>But this commit doesn't add or update <em>any</em> blog posts... so why is it being returned from <code>git log &#x3C;path/to/blogpost></code>?</p>
<p>What if I <code>git log</code>ged a file that has <em>definitely</em> been around since the first commit, like <code>index.tsx</code>. I tried printing out every log line for this file and saw the following on Vercel</p>
<pre><code>lines returned from git log index.tsx
69e038a919e448251fa2211a9fcf3fda914812fe @ 2022-01-09T20:48:23+00:00
88c420835d35a008de808b7cef04980a15b029bc @ 2022-01-09T12:55:49+00:00
0a882cf5062e4c0ac4505ed609ca77f14b35a76a @ 2022-01-08T20:15:44+00:00
d4a9a360c38398cdd41825aa0fe193e8176cb4fd @ 2022-01-07T22:41:52+00:00
3acb76c1f6c6d1b4cdb76939496e251220aa29ea @ 2022-01-06T20:09:17+00:00
</code></pre>
<p>It only goes back five commits! The commit history looked the same for other long-lived files as well. Only ever going back to that last commit on January 6.</p>
<p>Running the same code on my local machine gives many more commits, going back all the way to the first commit on January 2.</p>
<p>What gives?</p>
<h2>The Shallow End</h2>
<p>At this point, I wasn't sure how much more debugging I could do. So I started doing a bit of research.</p>
<p>And I found <a href="https://github.com/vercel/vercel/discussions/5737">this issue ("How to unshallow repo?")</a> on the Vercel GitHub repo</p>
<blockquote>
<p><em>"Hello, I need to define a variable at build time that depends on <code>git describe</code> which depends on git history, but it seems the repo in vercel build enviroment is a shallow clone with only few last commits."</em></p>
</blockquote>
<p>That sounds like my problem! And it sounds like it's caused by Vercel making <a href="https://www.perforce.com/blog/vcs/git-beyond-basics-using-shallow-clones">a <em>shallow clone</em> of my git repo</a> before building. I'd never encountered shallow cloning <em>in the wild</em> before, but I knew of it as a concept, which is how I found that GitHub issue.</p>
<p>So how can we work around this? We simply won't have the information available at build time to determine the correct "published" and "last updated" dates for a given blog post.</p>
<p>But there's always a way to work around these kinds of limitations. In this case, that involves a cache.</p>
<h2>Cache Rules Everything Around Me</h2>
<p>There are a few ways we could solve this problem. We could, for instance, use the GitHub API to pull commit information from the repo hosted on GitHub.com. I chose not to do this as I preferred to keep the solution self-contained: we have all the information available at build time <em>when running locally</em>, so how could we make that information available when building <em>for production</em> (on Vercel), as well? (Where we'll have a shallow clone of the repo.)</p>
<p>Rather than make API calls over the internet for information which is available locally, I thought we could simply save this information in a cache, and then use that cache when building on Vercel.</p>
<p>The workflow I came up with for writing blog posts (and caching the important git info) looked something like this</p>
<ol>
<li>draft a <code>wip-</code> post (these are <a href="https://github.com/awwsmm/awwsmm.com/blob/4281812447b58b08bcd613530e4d8db2b1855be6/.gitignore#L23">ignored for version control by my <code>.gitignore</code></a>)</li>
<li>when the draft is ready, <code>git commit</code> it to the <code>development</code> branch and push to Vercel</li>
<li>for...
<ul>
<li>new blog posts (where the only commit in <code>git log</code> is the current commit), Vercel assumes the post is brand-new and uses the date of the current commit for the "published" and "last updated" times</li>
<li>old blog posts (where more than one commit references this blog post), Vercel looks for cached "published" and "last updated" times, and throws an error if it doesn't find any</li>
</ul>
</li>
</ol>
<p>There are a few small problems with this.</p>
<p>First, when do we update the cache? You'll notice that there is no step in the workflow above for ensuring that the cache is up-to-date. Since we only have access to the required information when building locally, we have to update the cache when building locally. But when does this information get pushed to the remote repo? We have to enforce that, as well.</p>
<p>Second, the above workflow has a problem when we merge the <code>development</code> branch into the <code>master</code> branch when promoting a new release to production -- the merge commit itself means that the "new" blog post is now in two commits. As outlined above, this will cause Vercel to throw an error if the post isn't in the cache (it won't be).</p>
<h2>So... What Now?</h2>
<p>I've got some hacky fixes for the above problems implemented.</p>
<p>For instance, I've got a <a href="https://github.com/awwsmm/awwsmm.com/blob/4281812447b58b08bcd613530e4d8db2b1855be6/git-hooks/pre-push">pre-push git hook</a> which runs a build before each <code>git push</code>. This means that -- in theory -- the cache is always up to date. But of course, I need to make sure to <code>git add</code> it in the <em>next</em> commit.</p>
<p>As for the "merging creates a new commit" issue, I've tried two solutions so far.</p>
<p>The first was to distinguish between commits on the <code>development</code> branch and commits on the <code>master</code> branch. Only blog posts with commits on <code>master</code> should be considered as "old". This works great when running locally, but the clone that Vercel creates seems to <em>rename</em> this <code>development</code> branch to <code>master</code> when building a preview deployment. So that's a no-go.</p>
<p>The second solution (which I'm currently using) is to simply <a href="https://github.com/awwsmm/awwsmm.com/blob/4281812447b58b08bcd613530e4d8db2b1855be6/lib/blog/SlugFactory.ts#L28">ignore merge commits</a>.</p>
<p>So far, the above appears to be working. But it feels like an overly complex and fragile solution, and I hope to improve upon it in the future. Maybe just querying GitHub for the commit history is easier than going through all of this cache trouble.</p>
<h2>Conclusion</h2>
<p>So that's it! The goal was simple: get rid of arbitrary "published" times on blog posts and pull that data directly from the project's git history. But the solution ended up being much more complex and nuanced than I had initially planned.</p>
<p>But along the way, I learned some new tools and tricks, I learned a bit more about how my repo is built and deployed on Vercel, and I have some ideas for how I can make things more streamlined in the future. And that's what this is all meant to be, really, a learning experience.</p>
<p>In the future, maybe I'll do away with this overly-complex caching mechanism, but I do want to get the "published" and "last updated" dates from the repo's git history. This initial solution, while messy, does the job for now.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[What's Wrong This Time? Part II: Electric Bugaloo]]></title>
            <link>https://awwsmm.com/blog/whats-wrong-this-time-part-2</link>
            <guid isPermaLink="false">whats-wrong-this-time-part-2</guid>
            <pubDate>Sun, 23 Jan 2022 00:00:00 GMT</pubDate>
            <description><![CDATA[Debugging a New Feature in a Vercel TypeScript GitHub Repo]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><p><strong>Part II: The Bugs</strong></p>
<p>There's an old programming joke that goes <a href="https://martinfowler.com/bliki/TwoHardThings.html">something like</a></p>
<blockquote>
<p><em>There are only two hard problems in computer science: cache invalidation, naming things, and off-by-one errors.</em></p>
</blockquote>
<p>I think we should add a third (fourth?) problem to that list: sorting things.</p>
<h2>Sorting Things</h2>
<p>There are <a href="https://en.wikipedia.org/wiki/Sorting_algorithm">lots of different ways to sort things</a> in computer science. C.S. students learn about time and space complexity of these sorting algorithms, YouTubers make <a href="https://www.youtube.com/watch?v=BeoCbJPuvSE">cool visualisations</a> of them, and occasionally, <a href="https://en.wikipedia.org/wiki/Timsort">a guy named Tim</a> will invent a new one.</p>
<p>But there's one aspect of sorting algorithms that -- for me, at least -- seems completely impossible: remembering in which direction things are sorted.</p>
<p>If you say to a group of people: "okay, everyone, stand in a single-file line, ordered by height", the next question you might ask is "okay, but in which direction?" Who should stand at the <em>front</em> of the line? The shortest person or the tallest person?</p>
<p>In programming, we define comparison functions, which describe how to order whatever objects we're interested in.</p>
<p>Some comparison functions seem obvious. For example, in TypeScript, using the default <code>string</code> comparison...</p>
<pre><code class="hljs language-ts">const array: string[] = ["cherry", "apple", "banana"]
array.sort()
//...
</code></pre>
<p>...we would expect <code>array</code> to be sorted alphabetically, with <code>apple</code> as the first (<code>0</code>th) element of the sorted array</p>
<pre><code class="hljs language-ts">//...
console.log(array)    // [ 'apple', 'banana', 'cherry' ]
console.log(array[0]) // apple
</code></pre>
<blockquote>
<p>Note that <code>&#x3C;array>.sort()</code> in JavaScript sorts the array "in place", so that the original, unsorted <code>array</code> no longer exists afterward. In some languages, and for some sorting algorithms, arrays are not sorted in place, and a new array will be returned. This new array should be assigned to a new variable.</p>
</blockquote>
<p>But often we will be working with objects more complex than <code>string</code>s, and we will need to define custom comparison functions. These are functions which take two elements of type <code>T</code> and return a <code>number</code>, and are used to sort arrays of type <code>T</code>:</p>
<pre><code class="hljs language-ts">type T = string

const newArray: T[] = ["cherry", "apple", "banana"]

function comparison(t1: T, t2: T): number {
  return t1.charCodeAt(0) - t2.charCodeAt(0)
}

newArray.sort(comparison)

console.log(newArray)    // ?
console.log(newArray[0]) // ?
</code></pre>
<p>Without <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">reading the docs</a>, will the <code>console.log()</code>s above give the same result as the earlier ones? How about something a bit simpler -- sorting an array of <code>number</code>s:</p>
<pre><code class="hljs language-ts">type T = number

const newArray: T[] = [42, 2112, 19]

function comparison(t1: T, t2: T): number {
  return t2 - t1
}

newArray.sort(comparison)

console.log(newArray)    // ?
console.log(newArray[0]) // ?
</code></pre>
<p>Will the first element above be <code>19</code>? Or <code>2112</code>? Are you sure?</p>
<p>I understand the utility of sorting algorithms, and I understand the need for a ternary (greater than, less than, or equal) return value, and hence <code>number</code> as the return type instead of <code>boolean</code>, but comparison functions are just one of those things that I've always had to test every time. Sometimes in development, and sometimes in production.</p>
<h2>So What Happened?</h2>
<p>With what we learned above, you should now be able to see what went wrong with <a href="https://github.com/awwsmm/awwsmm.com/commit/69e038a919e448251fa2211a9fcf3fda914812fe">my initial code</a>. The problem was here</p>
<pre><code class="hljs language-ts">    // get the blog post date from its git commit date
    const gitLog = SlugFactory.git.log({ file: `blog/${slug.params.slug}.md` });

    return gitLog.then(lines => {
      const dates = lines.all.map(each => each.date);

      // if blog post hasn't been committed yet, use current date
      const date = dates[0] ?? new Date().toISOString();

      return new FrontMatter(slug.params.slug, title, description, date, rawContent);
    });
</code></pre>
<p><code>git log</code> returns commits sorted by date, such that <em>newer</em> commits come first and <em>later</em> commits come afterward. So <code>dates[0]</code>, above, is the <em>newest commit</em> returned from <code>git log</code>, and each blog post was being given a "publication" date of the most recent commit in which that post was modified.</p>
<p>When were these blog posts most recently modified? Well, all of them were modified in <a href="https://github.com/awwsmm/awwsmm.com/commit/69e038a919e448251fa2211a9fcf3fda914812fe">that same commit</a>, because the point of the commit was to remove the <code>date</code> parameter from the front matter. Essentially, I was mixing up the <code>lastUpdated</code> date and the <code>published</code> date. One of these is the first element in the list (<code>dates[0]</code>) and one of them is the last element in the list (<code>dates[dates.length-1]</code>).</p>
<p>So like I said, there are four hard problems in computer science.</p>
<h2>On To The Next One</h2>
<p>With that fixed, we're off to the races, right?</p>
<p><img src="https://i.imgur.com/ME7yZQ9.png" alt="Screenshot from awwsmm.com showing blog posts with incorrect dates"></p>
<p>Oh... well, that's not right.</p>
<p>Those two posts were both committed on January 2 (<a href="https://github.com/awwsmm/awwsmm.com/commit/ec96618d38c71134f4a9ed14d6ae6d7a2b5c9e59">Hello, World!</a> and <a href="https://github.com/awwsmm/awwsmm.com/commit/b2e504f52e4df0ddf77c662903e39b4aaf12f242">Git Hooks</a>), not on January 6. So why did they both have the wrong date?</p>
<p>That's right, it's another bug... Or is it?</p>
<p>Find out in <a href="https://www.awwsmm.com/blog/whats-wrong-this-time-part-3">the <em>thrilling</em> final installation of this debugging mystery!</a></p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[What's Wrong This Time? A Debugging Mystery in Three Parts]]></title>
            <link>https://awwsmm.com/blog/whats-wrong-this-time-part-1</link>
            <guid isPermaLink="false">whats-wrong-this-time-part-1</guid>
            <pubDate>Sun, 16 Jan 2022 00:00:00 GMT</pubDate>
            <description><![CDATA[Debugging a New Feature in a Vercel TypeScript GitHub Repo]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><p><strong>Part I: The Idea</strong></p>
<h2><em>"I have an idea"</em>*, I said to myself.</h2>
<p>"What if, instead of adding arbitrary dates to blog posts as I write them, I just got the dates from git?"</p>
<blockquote>
<p><a href="https://git-scm.com/">Git</a> is a <a href="https://www.atlassian.com/git/tutorials/what-is-version-control">version control system</a> used by software developers which tracks changes to files, as well as creation and deletion of files. Every change, addition, or deletion is timestamped and has a <a href="https://en.wikipedia.org/wiki/Hash_function">hash</a> which uniquely identifies those changes, like a fingerprint.</p>
</blockquote>
<p>"<a href="https://github.com/awwsmm/awwsmm.com/commits/master">Each git commit</a> has a date, so I should be able to programatically determine when a file in my <a href="https://www.gitkraken.com/learn/git/tutorials/what-is-a-git-repository">repo</a> was added, or edited."</p>
<p>That was my idea for simplifying the metadata ("front matter") that I add to each of my blog post files on <a href="https://github.com/awwsmm/awwsmm.com">my website</a>. Before this adventure, that metadata looked <a href="https://raw.githubusercontent.com/awwsmm/awwsmm.com/ec96618d38c71134f4a9ed14d6ae6d7a2b5c9e59/blog/hello-world.md">something like this</a>:</p>
<pre><code class="hljs language-txt">---
title: 'Hello, World!'
description: 'Rewriting My Personal Website in Next.js and TypeScript'
date: '2022-01-01'
---
</code></pre>
<p>What I wanted to do was get rid of that arbitrary <code>date</code> field I was adding to every blog post, and just let git tell me when I published or updated a file. I could pull this information from the history of file changes that git keeps track of.</p>
<p>Sounds relatively simple, right?</p>
<p>Well, there were a few roadblocks to getting this up and running. Before we get into them, let's take a look at my initial, quick-and-dirty solution.</p>
<h2>First Attempt</h2>
<h3>Git background</h3>
<p>When working locally (on your personal computer), you can interact with git using the command line. One command, <a href="https://git-scm.com/docs/git-log"><code>git log</code></a>, gives a list of all of the changes saved ("committed") to the project</p>
<pre><code class="hljs language-txt">$ git log --oneline -n 5
b6eea85 (HEAD -> master, origin/master, origin/HEAD) Merge pull request #15 from awwsmm/development
bc222b3 (origin/development, development) automatically date blog posts using git history
88c4208 order blog posts on index page reverse chronologically
9368f24 new blog post about nominal, structural, and duck typing
6bbe307 Merge pull request #1 from awwsmm/development
</code></pre>
<p>The options I passed to <code>git log</code>, <code>--oneline</code> and <code>-n 5</code>, tell git that I only want one line of minimal information for each commit (just the hash and the first line of the commit message), and that I only want the five most recent commits. By default, git shows something like</p>
<pre><code class="hljs language-txt">$ git log
commit b6eea85256fe54f34013f17aca4e892aba0778dd (HEAD -> master, origin/master, origin/HEAD)
Merge: 88c4208 bc222b3
Author: Andrew &#x3C;aww@awwsmm.com>
Date:   Fri Jan 14 19:01:11 2022 +0000

    Merge pull request #15 from awwsmm/development

    automatically date blog posts using git history
</code></pre>
<p>...with the commit hash, the commit message, the date of the commit, the author, and so on. But lots of other options can be set for <code>git log</code>, for instance, specifying a hash will show only that commit and its ancestors (commits that came before it), and <code>--name-only</code> shows the names of all files modified in that commit</p>
<pre><code class="hljs language-txt">$ git log bc222b3 --name-only -n 1
commit bc222b37913ec2cdd7ff5f152dfaca06d33ec9f3 (origin/development, development)
Author: Andrew Watson &#x3C;aww@awwsmm.com>
Date:   Fri Jan 14 18:54:39 2022 +0000

    automatically date blog posts using git history

.gitignore
README.md
blog/cache.json
blog/git-commit-hooks.md
blog/hello-world.md
blog/nominal-vs-structural-vs-duck-typing.md
lib/blog/FrontMatterFactory.ts
lib/blog/SlugFactory.ts
package-lock.json
package.json
pages/blog/[slug].tsx
pages/index.tsx
</code></pre>
<p>You can also pass a file path to <code>git log</code> and it will only show you commits in which that file was modified</p>
<pre><code class="hljs language-txt">$ git log blog/hello-world.md
commit bc222b37913ec2cdd7ff5f152dfaca06d33ec9f3 (origin/development, development)
Author: Andrew Watson &#x3C;aww@awwsmm.com>
Date:   Fri Jan 14 18:54:39 2022 +0000

    automatically date blog posts using git history

commit ec96618d38c71134f4a9ed14d6ae6d7a2b5c9e59
Author: Andrew Watson &#x3C;aww@awwsmm.com>
Date:   Sun Jan 2 12:11:54 2022 +0000

    attempting to deploy to Vercel
</code></pre>
<p>That's all well and good, but I wanted to get this information when building my website, which is written in TypeScript. So I would need a TypeScript or a JavaScript library to be able to do this easily. That's where <a href="https://www.npmjs.com/package/simple-git"><code>simple-git</code></a> comes in.</p>
<h3>Git in TypeScript</h3>
<p><code>simple-git</code> is a JavaScript library which <a href="https://github.com/steveukx/git-js">allows you to run git commands</a> from within TypeScript / JavaScript code.</p>
<p>For instance, instead of the above <code>git log blog/hello-world.md</code>, we can write something like</p>
<pre><code class="hljs language-ts">import simpleGit from 'simple-git'

const git = simpleGit()
const logResult = await git.log({ file: 'blog/hello-world.md' })
const commits = logResult.all
</code></pre>
<p>Then, we can loop over all commits and easily access each commit's data</p>
<pre><code class="hljs language-ts">commits.forEach(commit => {        // example:
  console.log(commit.author_email) // aww@awwsmm.com
  console.log(commit.author_name)  // Andrew Watson
  console.log(commit.body)         //
  console.log(commit.date)         // 2022-01-14T18:54:39+00:00
  console.log(commit.diff)         // null
  console.log(commit.hash)         // bc222b37913ec2cdd7ff5f152dfaca06d33ec9f3
  console.log(commit.message)      // automatically date blog posts using git history
  console.log(commit.refs)         // origin/development, development
})
</code></pre>
<p>So that should be it: when compiling the project, we should be able to use this library to get all log lines which refer to a specific file. The most recent one should be the <code>lastUpdated</code> date of the file, while the least recent one should be the <code>published</code> date of the file.</p>
<p><a href="https://github.com/awwsmm/awwsmm.com/commit/69e038a919e448251fa2211a9fcf3fda914812fe">I quickly coded this up</a>, ran it locally, and everything looked fine. I thought that would be the end of the story.</p>
<p>But then I pushed it to production.</p>
<h2>First Problem</h2>
<p>The first problem I hit was that all of my blog posts now had the same date (which at the time was the current date):</p>
<p><img src="https://i.imgur.com/C0WGWdp.png" alt="Screenshot of awwsmm.com showing multiple blog posts with the same date"></p>
<p>Do you see any problems with <a href="https://github.com/awwsmm/awwsmm.com/commit/69e038a919e448251fa2211a9fcf3fda914812fe">the code I wrote here?</a></p>
<p>What's going on here?</p>
<p>Check out the answer in <a href="https://www.awwsmm.com/blog/whats-wrong-this-time-part-2">the second part of this series</a>.</p>
<hr>
<blockquote>
<p>* This is the traditional phrase for conjuring bugs in your programs. See also: <em>"I'll just do a little refactoring"</em>.</p>
</blockquote></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[What's the Difference Between Nominal, Structural, and Duck Typing?]]></title>
            <link>https://awwsmm.com/blog/nominal-vs-structural-vs-duck-typing</link>
            <guid isPermaLink="false">nominal-vs-structural-vs-duck-typing</guid>
            <pubDate>Sun, 09 Jan 2022 00:00:00 GMT</pubDate>
            <description><![CDATA[Nominal, Structural, and Duck Typing in Java, TypeScript, and JavaScript]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><h2>Nominal Typing</h2>
<p>Most major programming languages with objects use <a href="https://en.wikipedia.org/wiki/Nominal_type_system">nominal typing</a>, where the <em>name</em> (or <a href="https://en.wikipedia.org/wiki/Fully_qualified_name">fully qualified class name, FQCN</a>) of an object determines whether or not it is equal to another object, or assignable to a variable of a particular type. <a href="https://www.mycompiler.io/view/BDKXhWg">For example, in Java</a></p>
<pre><code class="hljs language-java">class Dog {
  public String name;
  public Dog (String name) {
    this.name = name;
  }
}

class Person {
  public String name;
  public Person (String name) {
    this.name = name;
  }
}
</code></pre>
<p>If you create a <code>Dog</code> and a <code>Person</code> with the same <code>name</code>, <a href="https://www.mycompiler.io/view/JJSt7fK">Java will tell you that they're not the same thing</a>, even though both classes have the same <em>structure</em> (a single <code>String</code> field named <code>name</code>) and the same internal state (<code>name</code> is <code>"Fido"</code>)</p>
<pre><code class="hljs language-java">Dog dog = new Dog("Fido");
Person person = new Person("Fido");

// System.out.println(dog == person); // error: incomparable types: Dog and Person
System.out.println(dog.equals(person)); // false
System.out.println(person.equals(dog)); // false
</code></pre>
<p>And <a href="https://www.mycompiler.io/view/88L7lwy">you cannot pass a <code>Dog</code> to a method which expects a <code>Person</code></a></p>
<pre><code class="hljs language-java">class Greeter {
    public static void greet (Person person) {
        System.out.println("Hello, " + person.name + "!");
    }
}

// ...

Greeter.greet(person); // Hello, Fido!
// Greeter.greet(dog); // error: incompatible types: Dog cannot be converted to Person
</code></pre>
<h2>Structural Typing</h2>
<p>In contrast, TypeScript allows for <em>structural typing</em> in some scenarios, where the structure of the objects is all that matters (and class names are immaterial). If we had the following two classes in TypeScript, we will see -- similar to Java -- that <a href="https://www.typescriptlang.org/play?#code/MYGwhgzhAEAiD2BzaBvAUNaA7MBbApgFzQQAuATgJZaIbTDxZnkCuwp850AFDgcc2qIAlKjqZSAC0oQAdH3zQAvNjz4A3HQC+aHWlCQYABXzkIjMZgUCKQugyYU2HLrzU2qNUekwTpchWVVAk1MHT0HMmgAEyQgrHwAdzgkbgAiADFKWLThTUjSaAAHU3MseKToEzNGdKycvLR9RnMQfFkQVNjkJRUSmqw86AB6YegAMzAQCHwgA">they are not equal when compared with <code>==</code></a></p>
<pre><code class="hljs language-ts">class Dog {
  name: string
  constructor (name: string) {
    this.name = name;
  }
}

class Person {
  name: string
  constructor (name: string) {
    this.name = name;
  }
}

const dog = new Dog("Fido");
const person = new Person("Fido");

console.log(dog == person); // false
</code></pre>
<p>But suppose <a href="https://www.typescriptlang.org/play?#code/MYGwhgzhAEAiD2BzaBvAUNaA7MBbApgFzQQAuATgJZaIbTDxZnkCuwp850AFDgcc2qIAlKjqZSAC0oQAdH3zQAvNjz4A3HQC+aHWlCQYABXzkIjMZgUCKQugyYU2HLrzU2qNUekwTpchWVVAk1MHT0HMmgAEyQgrHwAdzgkbgAiADFKWLThTUjSaAAHU3MseKToEzNGdKycvLR9RnMQfFkQVNjkJRUSmqw86AB6YegAMzAQCHwmgyhoAHFyfHxSU0sSUjBSSmBoRBW1nkPV7YAjNuIUYKItz2Qtb3F6Fvg2jtSAAwAJfBBOgAaaAAEhQpzWYEu7QUWgAhF9GmFdE1lmdTLIIaRuP0ykNRtA-gD4MD6vA4Wg0WsMVjuN18WMiUDoGS4UA">we write our <code>Greeter</code> class in TypeScript as</a></p>
<pre><code class="hljs language-ts">class Greeter {
  static greet (greetable: { name: string }) {
    console.log(`Hello, ${greetable.name}!`);
  }
}

Greeter.greet(person); // Hello, Fido!
Greeter.greet(dog); // Hello, Fido!
</code></pre>
<p>TypeScript simply checks that the object passed to <code>greet()</code> has a <code>name: string</code> field, because that's the type we specified for <code>greetable</code>: an object with a <code>name: string</code> field. It doesn't care what class <code>greetable</code> might be, <a href="https://www.typescriptlang.org/play?#code/MYGwhgzhAEAiD2BzaBvAUNaA7MBbApgFzQQAuATgJZaIbTDxZnkCuwp850AFDgcc2qIAlKjqZSAC0oQAdH3zQAvNjz4A3HQC+aHWlCQYABXzkIjMZgUCKQugyYU2HLrzU2qNUekwTpchWVVAk1MHT0HMmgAEyQgrHwAdzgkbgAiADFKWLThTUjSaAAHU3MseKToEzNGdKycvLR9RnMQfFkQVNjkJRUSmqw86AB6YegAMzAQCHwmgyhoAHFyfHxSU0sSUjBSSmBoRBW1nkPV7YAjNuIUYKItz2Qtb3F6Fvg2jtSAAwAJfBBOgAaaAAEhQpzWYEu7QUWgAhF9GmFdE1lmdTLIIaRuP0ykNRtA-gD4MD6vA4Wg0WsMVjuN18WMiUDoGSKfpwAsAEKUcjRTYMTrkDx2Kzue4i16OVjsTg8AWcYU0YHWcVeTZ+GSyeVcFTa0K+KSawIqBT68JzFqFc48vkmyrc3npFbRNLAtKc+AATxdjSp63ImKO2OtvIZhP+zI93rhQA">or if it has other fields and methods as well</a></p>
<pre><code class="hljs language-ts">class Bird {
  color: string
  name: string
  constructor (color: string, name: string) {
    this.color = color;
    this.name = name;
  }
}

const bird = new Bird("red", "Boyd");
Greeter.greet(bird); // Hello, Boyd!
</code></pre>
<h2>Duck Typing</h2>
<p>In JavaScript, we might <a href="https://jsfiddle.net/y5vts2Lk/">rewrite the above TypeScript classes like</a></p>
<pre><code class="hljs language-js">class Dog {
  constructor (name) {
    this.name = name;
  }
}

class Person {
  constructor (name) {
    this.name = name;
  }
}

class Bird {
  constructor (color, name) {
    this.color = color;
    this.name = name;
  }
}

const dog = new Dog("Fido");
const person = new Person("Fido");
const bird = new Bird("red", "Boyd");
</code></pre>
<p>But, as JavaScript doesn't specify types using the <code>:</code> as TypeScript does, we also have to <a href="https://jsfiddle.net/y5vts2Lk/1/">rewrite our <code>Greeter</code> slightly</a></p>
<pre><code class="hljs language-js">class Greeter {
  static greet (greetable) {
    console.log("Hello, " + greetable.name + "!");
  }
}

Greeter.greet(person); // Hello, Fido!
Greeter.greet(dog); // Hello, Fido!
Greeter.greet(bird); // Hello, Boyd!
</code></pre>
<p>In this case, there are no type or structural constraints at all on <code>greetable</code>. JavaScript is using <a href="https://en.wikipedia.org/wiki/Duck_typing">duck typing</a> here, where field and method accesses are only checked at runtime (and not at compile time, because JavaScript isn't compiled). If a <code>greetable</code> has all of the required fields, no errors will be thrown.</p>
<p>However, <a href="https://jsfiddle.net/bjgz7cuo/">if a field is missing...</a></p>
<pre><code class="hljs language-js">class Complimenter {
  static compliment (target) {
    console.log("Hello, " + target.name + "!");
    console.log("What a nice shade of " + target.color + " you are!");
  }
}

Complimenter.compliment(person); // Hello, Fido! What a nice shade of undefined you are!
Complimenter.compliment(dog); // Hello, Fido! What a nice shade of undefined you are!
Complimenter.compliment(bird); // Hello, Boyd! What a nice shade of red you are!
</code></pre>
<p>...we can get <code>undefined</code> results.</p>
<blockquote>
<p>The name "duck typing" comes from the phrase <a href="https://en.wikipedia.org/wiki/Duck_test">"If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck"</a>. When using duck typing, we run the program as long as we can until we hit a runtime error -- until the "duck" no longer looks like a duck.</p>
</blockquote></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[Hello, World!]]></title>
            <link>https://awwsmm.com/blog/hello-world</link>
            <guid isPermaLink="false">hello-world</guid>
            <pubDate>Sun, 02 Jan 2022 00:00:00 GMT</pubDate>
            <description><![CDATA[Rewriting My Personal Website in Next.js and TypeScript]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><p>New Year's Day is as good a time as any to roll out a new blog, I suppose.</p>
<p>As one of my New Year's Resolutions this year, I'm going to revamp my website, and I'm going to do it in public.</p>
<p>I've spent the last few weeks working with Next.js for the first time (and brushing up on my TypeScript) in order to start hosting my technical blog on my own website. (In addition to mirroring the posts <a href="https://dev.to/awwsmm">on Dev.to</a>, where I've been writing for a few years now.)</p>
<p>In addition to the ol' blog, I've also created <strong>/project</strong> pages for a few ongoing things I've got in the works (including this very website). The project pages synthesize groups of commits from GitHub with manual "update" log posts to give an idea as to the current status of each of my ongoing projects. I think this is a bit more dynamic than a static "portfolio" page, and it reflects a tenet of my own personal philosophy that <a href="https://quoteinvestigator.com/2019/03/01/abandon/"><em>un ouvrage n’est jamais achevé... mais abandonné</em></a>.</p>
<p>Follow along here, <a href="https://dev.to/awwsmm">on Dev.to</a>, or <a href="https://twitter.com/awwsmm_dot_com">on Twitter</a> for continuing updates.</p>
<p>Thanks for reading!</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[Eliminate Unnecessary Builds With Git Hooks]]></title>
            <link>https://awwsmm.com/blog/git-commit-hooks</link>
            <guid isPermaLink="false">git-commit-hooks</guid>
            <pubDate>Sun, 02 Jan 2022 00:00:00 GMT</pubDate>
            <description><![CDATA[Writing Git Commit Hooks in Bash, Java, and Scala]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><h2>Writing a Git Hook in Bash</h2>
<p><a href="https://www.atlassian.com/git/tutorials/git-hooks">Git Hooks</a> can be a very useful addition to a developer's workflow.</p>
<p>For instance, as I'm working on <a href="https://www.awwsmm.com/blog/hello-world">rewriting my new website using Next.js</a>, I've set up <a href="https://eslint.org">eslint</a> and have pretty strict linting rules when running Next builds.</p>
<p>Unfortunately, Git doesn't follow these rules by default. So it's easy to forget to run the linter, run a <code>git push</code>, and end up with a failing production build on <a href="https://vercel.com">Vercel</a>.</p>
<p>To avoid this, I've set up a simple Git Hook which runs <code>eslint</code> before every <code>git push</code>, and fails the <code>push</code> if the linter returns any <code>error</code>s:</p>
<pre><code class="hljs language-sh"># .git/hooks/pre-push

# pipe output (with colors) to .temp file
RESULT=$(script -q .temp npm run lint)

# if .temp file contains "error", fail
if grep --quiet error .temp; then
  printf "\n  !! Will not push -- found linting errors:\n"
  sed '1,5d' .temp | cat
  rm .temp
  exit 1
else
  rm .temp
  exit 0
fi
</code></pre>
<p>The above script runs <code>npm run lint</code>, captures the output (<a href="https://stackoverflow.com/a/3515296/2925434">with text colors</a>) to a <code>.temp</code> file, and then <code>grep</code>s for <code>error</code> in that file. If it finds any instances of the word "error", it won't <code>push</code>, but will instead print the output of the <code>npm run lint</code> command:</p>
<pre><code class="hljs language-sh">$ git push

  !! Will not push -- found linting errors:

/Users/andrew/Git/awwsmm.com/components/CommitGroupComponent.tsx
   2:1  error  Imports should be sorted alphabetically  sort-imports
  24:4  error  Missing semicolon                        semi

✖ 2 problems (2 errors, 0 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.

error: failed to push some refs to 'github.com:awwsmm/awwsmm.com.git'
</code></pre>
<p>This prevents useless builds on Vercel which will fail because of linting errors.</p>
<p><strong>Note:</strong> make sure your <code>.git/hooks/&#x3C;file></code> is executable (<code>chmod +x .git/hooks/&#x3C;file></code>), or it will not prevent the particular action from occurring. It's probably best to play around with a <code>pre-commit</code> hook rather than a <code>pre-push</code> one, when testing.</p>
<h2>Writing a Git Hook in Java</h2>
<p>We can do a similar thing using Java instead of bash scripting. For this example, we'll look at writing a <code>pre-commit</code> hook in Java. Instead of writing Java code to the <code>pre-commit</code> file directly, we'll add a bit of indirection.</p>
<p>First, create a file called <code>PreCommit.java</code> in the <code>.git/hooks/</code> directory and add some pre-commit logic to it. In this case, we're just going to fail every commit:</p>
<pre><code class="hljs language-java">public class PreCommit {
  public static void main (String[] args) {
    System.out.println("Java says: no committing please.");
    System.exit(1);
  }
}
</code></pre>
<p>The <code>System.exit(1)</code> gives the same result as <code>exit 1</code> in the Bash script -- the commit will fail to complete.</p>
<p>Next, we'll make the <code>.git/hooks/pre-commit</code> file executable with</p>
<pre><code class="hljs language-sh">$ chmod +x .git/hooks/pre-commit
</code></pre>
<p>...and modify its contents to read:</p>
<pre><code class="hljs language-sh">#!/bin/sh

# get the path to this script file
DIR=$(dirname "$0")

# Java >= 11
exec java $DIR/PreCommit.java "$@"
</code></pre>
<blockquote>
<p>If you're using Java 11+, you can also write this <a href="https://stackoverflow.com/a/61899256/2925434">all as a single file</a>, though I personally don't recommend this method as it combines Bash and Java syntax in a single file, which can be difficult for IDEs to handle in terms of syntax highlighting, etc.</p>
</blockquote>
<p>With this in place, we'll now see a message like</p>
<pre><code class="hljs language-sh">$ git commit -m "update gitignore, more hook testing"
Java says: no committing please.
</code></pre>
<p>Note that in Java versions &#x3C; 11, we need to compile this script first with <code>javac</code>, so <code>pre-commit</code> should instead look something like</p>
<pre><code class="hljs language-sh">#!/bin/sh
DIR=$(dirname "$0")

# Java &#x3C; 11
javac $DIR/PreCommit.java "$@"
exec java -classpath $DIR PreCommit
!#
</code></pre>
<h2>Writing a Git Hook in Scala</h2>
<p>The process for <a href="https://alvinalexander.com/scala/scala-shell-script-example-exec-syntax/">writing a Git Hook in Scala</a> is very similar to writing one in Java. First, define a <code>pre-commit.scala</code> file with the following contents</p>
<pre><code class="hljs language-scala"><span class="hljs-class"><span class="hljs-keyword">object</span> <span class="hljs-title">Hook</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span> </span>(args: <span class="hljs-type">Array</span>[<span class="hljs-type">String</span>]): <span class="hljs-type">Unit</span> = {
    <span class="hljs-type">System</span>.out.println(<span class="hljs-string">"Scala says: no committing please."</span>);
    <span class="hljs-type">System</span>.exit(<span class="hljs-number">1</span>);
  }
}
</code></pre>
<p>(Note that, in Scala, the name of the class doesn't have to match the name of the file.)</p>
<p>Then, modify the contents of <code>pre-commit</code> to read</p>
<pre><code class="hljs language-sh">#!/bin/sh
DIR=$(dirname "$0")
exec scala $DIR/pre-commit.scala "$@"
!#
</code></pre>
<p>Finally, try to commit:</p>
<pre><code class="hljs language-sh">$ git commit -m "update gitignore, more hook testing"
Scala says: no committing please.
</code></pre>
<p>That's all there is to it.</p>
<p>As it takes a while for the JVM to boot up when running Git Hooks in Java or Scala, it's probably not extremely practical to do so... unless you have a lot of logic in your hook which is easier to read in Java / Scala than in a Bash script.</p>
<p>But anyway, it's good to know that it can be done.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[Publish your Scala sbt Project to Maven in 5 Minutes with Sonatype]]></title>
            <link>https://awwsmm.com/blog/publish-your-scala-sbt-project-to-maven-in-5-minutes-with-sonatype</link>
            <guid isPermaLink="false">publish-your-scala-sbt-project-to-maven-in-5-minutes-with-sonatype</guid>
            <pubDate>Tue, 13 Jul 2021 00:00:00 GMT</pubDate>
            <description><![CDATA[Quickly and Easily Publish Your Scala Code for Use in Other Projects]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><h2>Intro</h2>
<p>Say what you will about JavaScript, but <a href="https://www.npmjs.com/">npm</a> has made it incredibly easy for anyone to publish code. In just a few clicks, you can share a library to make others' lives easier, or publish a little snippet like <a href="https://qz.com/646467/how-one-programmer-broke-the-internet-by-deleting-a-tiny-piece-of-code/"><code>left-pad</code></a> to cause endless headaches.</p>
<p>Java has long had the <a href="https://mvnrepository.com/">Maven repository</a> (and accompanying build tool of the same name), which serves a similar purpose: sharing packaged code.</p>
<p>But it can be intimidating for a newbie to publish to Maven -- that's where Sonatype comes in.</p>
<p>Sonatype, Inc.'s <a href="https://central.sonatype.org/">Central Repository</a> (a complement to Apache's Maven repository) makes it super easy to share code. With just a few lines and a few manual steps, you can publish your package to Maven, and others can easily import it and use it.</p>
<p>sbt's <a href="https://www.scala-sbt.org/release/docs/Using-Sonatype.html">Using Sonatype</a> guide and Sonatype's <a href="https://central.sonatype.org/publish/publish-guide/">Deployment Guide</a> cover probably 95% of what you need to know for this process, but there are a few <em>gotchas</em> that I'll highlight below using the ❗ exclamation point emoji.</p>
<blockquote>
<p>Note: this guide assumes that your source code is hosted in a GitHub or GitLab repository.</p>
</blockquote>
<h2>Steps</h2>
<h3>1. Create a Sonatype Jira issue</h3>
<p>Sonatype syncs with Maven, and so to publish to Maven, you can publish via Sonatype. To do so, you'll need a Sonatype Jira account to create an issue. Do that by <a href="https://issues.sonatype.org/secure/Signup!default.jspa">clicking here to create an account</a> and then <a href="https://issues.sonatype.org/secure/CreateIssue.jspa?issuetype=21&#x26;pid=10134">clicking here to create a Jira issue</a>.</p>
<p>As an example, <a href="https://issues.sonatype.org/browse/OSSRH-71079">here is the ticket I opened</a> to publish a project of mine to Maven. If you want to publish multiple packages to Maven using Sonatype, you'll need to create multiple Jira tickets, but you only need the one user account.</p>
<p>The fields in the Jira are easy to fill out:</p>
<h4>Summary</h4>
<p>This should include the name of the project. In my case, I'm publishing a small project hosted at <a href="https://github.com/awwsmm/zepto">https://github.com/awwsmm/zepto</a>, so I've included the name "zepto" in the Jira summary.</p>
<h4>Group Id</h4>
<p>If your project is hosted on GitHub, this should be something like <code>io.github.awwsmm</code>, or similar for your GitHub username. See <a href="https://central.sonatype.org/publish/requirements/coordinates/">this guide</a> for more information on package coordinates.</p>
<blockquote>
<p>❗ <strong>GOTCHA:</strong> this should <em>not</em> be something like <code>com.github.awwsmm</code>. <code>com.github</code> coordinates are no longer supported. It <em>can</em> be your personal website, like <code>com.awwsmm</code>, but <a href="https://issues.sonatype.org/browse/OSSRH-95101">a bot will comment on your Jira asking you to add a DNS record to prove that you own that website, like here on another one of my Jiras</a>.</p>
</blockquote>
<h4>Project URL</h4>
<p>This is where users can go on the web to find information about your project. For me, that's <code>https://github.com/awwsmm/zepto</code>, but it could be a <code>github.io</code> page or a page on your personal website, or whatever.</p>
<h4>SCM url</h4>
<p>This is the URL that your source code is hosted at. For me, that's <code>https://github.com/awwsmm/zepto.git</code>.</p>
<h3>2. Generate and distribute a PGP key</h3>
<h4>On macOS</h4>
<p>On macOS, I recommend that you use <a href="https://gpgtools.org/">https://gpgtools.org/</a> to create and distribute your PGP key. Simply download the installer and follow the instructions there.</p>
<p>To run <code>sbt publishSigned</code> later in this guide, you will also need <code>gpg2</code> and <code>pinentry</code> installed. You can get those on macOS via <code>brew</code> with</p>
<pre><code class="hljs language-bash">$ brew install gpg2
$ brew install pinentry-mac
</code></pre>
<p>Note that you need <code>gpg2</code> here, not <code>gpg</code>. You should <a href="https://stackoverflow.com/a/45932796/2925434">check if you have both installed and <code>brew uninstall gpg</code> if it exists</a></p>
<pre><code class="hljs language-bash">$ which gpg gpg2
</code></pre>
<p>Once you've done that, check that <code>gpg-agent</code> is correctly configured, and restart it by <code>--kill</code>ing it, per <a href="https://superuser.com/a/1628810/728488">these instructions</a>.</p>
<h4>On Linux</h4>
<p>We'll use a <a href="https://en.wikipedia.org/wiki/Pretty_Good_Privacy">PGP key</a> to sign this package, so users can be confident that you are the person who created it. To do this, you can mostly follow the instructions from <a href="https://www.scala-sbt.org/release/docs/Using-Sonatype.html">scala-sbt.org</a>...</p>
<p>Install <a href="https://www.gnupg.org/download/">GnuPG</a> (on macOS, you can do this via <code>brew install gnupg</code>) and verify that it's installed by checking the version</p>
<pre><code class="hljs language-bash">$ gpg --version
gpg (GnuPG) 2.3.1
...
</code></pre>
<p>Next, generate a key...</p>
<pre><code class="hljs language-bash">$ gpg --gen-key
</code></pre>
<p>...list your keys...</p>
<pre><code class="hljs language-bash">$ gpg --list-keys
gpg: checking the trustdb
gpg: marginals needed: 3  completes needed: 1  trust model: pgp
gpg: depth: 0  valid:   1  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 1u
gpg: next trustdb check due at 2023-07-11
/Users/andrew.watson/.gnupg/pubring.kbx
---------------------------------------
pub   ed25519 2021-07-11 [SC] [expires: 2023-07-11]
      1234517530FB96F147C6A146A326F592D39AAAAA
uid           [ultimate] Andrew Watson &#x3C;my@email.com>
sub   cv25519 2021-07-11 [E] [expires: 2023-07-11]
</code></pre>
<p>...and distribute the key to some GPG keyserver, like</p>
<pre><code class="hljs language-bash">$ gpg --keyserver keyserver.ubuntu.com --send-keys 
1234517530FB96F147C6A146A326F592D39AAAAA
gpg: sending key A326F592D39AAAAA to hkp://keyserver.ubuntu.com
</code></pre>
<blockquote>
<p>❗ <strong>GOTCHA:</strong> If you get an error like <code>keyserver send failed: No name</code> from the command above, it means the keyserver you're trying to send to is no longer active. <a href="https://stackoverflow.com/a/68132500/2925434">You can instead use any other major GPG keyserver</a>, like the Ubuntu one I used above.</p>
</blockquote>
<p><a href="https://leonard.io/blog/2017/01/an-in-depth-guide-to-deploying-to-maven-central/">Leonard notes here</a> that synchronising these keys around the various keyservers can take some time, but for me it worked almost instantly.</p>
<p>Once you publish your key, you can check that it's visible on the public keyservers by searching for it here: <a href="https://keys.openpgp.org/">https://keys.openpgp.org/</a>.</p>
<h3>3. Enable <code>sbt-pgp</code></h3>
<p><a href="https://www.scala-sbt.org/release/docs/Using-Sonatype.html">As outlined here</a>, you'll next want to add the <code>sbt-pgp</code> plugin to your project. You can add it to your project's <code>plugin.sbt</code> file, or you can add it to <code>~/.sbt/1.0/plugins/gpg.sbt</code> to enable it for all sbt projects. The line you should add is</p>
<pre><code class="hljs language-scala">addSbtPlugin(<span class="hljs-string">"com.github.sbt"</span> % <span class="hljs-string">"sbt-pgp"</span> % <span class="hljs-string">"2.2.1"</span>)
</code></pre>
<p>The latest version of this plugin can be found <a href="https://github.com/sbt/sbt-pgp">at the GitHub page for the project</a>.</p>
<h3>4. Add your Sonatype credentials to your project</h3>
<p>Next, add your credentials to your project by following the instructions in <a href="https://www.scala-sbt.org/release/docs/Using-Sonatype.html">Step 3</a> here. I'll reproduce them to be clear...</p>
<p>Create a file at</p>
<pre><code class="hljs language-bash">$HOME/.sbt/1.0/sonatype.sbt
</code></pre>
<p>And add the following line to it</p>
<pre><code class="hljs language-scala">credentials += <span class="hljs-type">Credentials</span>(<span class="hljs-type">Path</span>.userHome / <span class="hljs-string">".sbt"</span> / <span class="hljs-string">"sonatype_credentials"</span>)
</code></pre>
<p>Then, create the credentials file at</p>
<pre><code class="hljs language-bash">~/.sbt/sonatype_credentials
</code></pre>
<p>Add the following information to that file</p>
<pre><code>realm=Sonatype Nexus Repository Manager
host=s01.oss.sonatype.org
user=&#x3C;your username>
password=&#x3C;your password>
</code></pre>
<p>The <code>user</code> and <code>password</code> here are the same username and password you used when creating your account on Sonatype's Jira server in Step 1. You don't need to worry about putting anything in quotes here -- spaces are fine. But...</p>
<blockquote>
<p>❗ <strong>GOTCHA:</strong> ...be careful! Some older guides say to set <code>host=oss.sonatype.org</code>, but this has recently changed to <code>host=s01.oss.sonatype.org</code>. More information about this change <a href="https://central.sonatype.org/publish/release/">can be found here</a>.</p>
</blockquote>
<h3>5. Set up your <code>publish.sbt</code></h3>
<p>The penultimate step in this process is to configure your project for publishing, by adding a bunch of information to either your project's <code>build.sbt</code> (or, as I recommend) <code>publish.sbt</code> file.</p>
<p>Replace <code>username</code> with your GitHub / GitLab username below, <code>project</code> with the name of the project (in my case, these are <code>awwsmm</code> and <code>zepto</code>, respectively), and all the other obvious fill-in bits, and paste it into a <code>publish.sbt</code> file at the root of your project</p>
<pre><code class="hljs language-scala"><span class="hljs-type">ThisBuild</span> / organization := <span class="hljs-string">"io.github.username"</span>
<span class="hljs-type">ThisBuild</span> / organizationName := <span class="hljs-string">"username"</span>
<span class="hljs-type">ThisBuild</span> / organizationHomepage := <span class="hljs-type">Some</span>(url(<span class="hljs-string">"https://www.yourwebsite.com"</span>))

<span class="hljs-type">ThisBuild</span> / scmInfo := <span class="hljs-type">Some</span>(
  <span class="hljs-type">ScmInfo</span>(
    url(<span class="hljs-string">"https://github.com/username/project"</span>),
    <span class="hljs-string">"scm:git@github.username/project.git"</span>
  )
)

<span class="hljs-type">ThisBuild</span> / developers := <span class="hljs-type">List</span>(
  <span class="hljs-type">Developer</span>(
    id    = <span class="hljs-string">"username"</span>,
    name  = <span class="hljs-string">"Your Name Goes Here"</span>,
    email = <span class="hljs-string">"youremail@address.com"</span>,
    url   = url(<span class="hljs-string">"https://www.yourwebsite.com"</span>)
  )
)

<span class="hljs-type">ThisBuild</span> / description := <span class="hljs-string">"Describe your project here..."</span>
<span class="hljs-type">ThisBuild</span> / licenses := <span class="hljs-type">List</span>(<span class="hljs-string">"The Unlicense"</span> -> <span class="hljs-keyword">new</span> <span class="hljs-type">URL</span>(<span class="hljs-string">"https://unlicense.org/"</span>))
<span class="hljs-type">ThisBuild</span> / homepage := <span class="hljs-type">Some</span>(url(<span class="hljs-string">"https://github.com/username/project"</span>))

<span class="hljs-comment">// Remove all additional repository other than Maven Central from POM</span>
<span class="hljs-type">ThisBuild</span> / pomIncludeRepository := { _ => <span class="hljs-literal">false</span> }

<span class="hljs-type">ThisBuild</span> / publishTo := {
  <span class="hljs-keyword">val</span> nexus = <span class="hljs-string">"https://s01.oss.sonatype.org/"</span>
  <span class="hljs-keyword">if</span> (isSnapshot.value) <span class="hljs-type">Some</span>(<span class="hljs-string">"snapshots"</span> at nexus + <span class="hljs-string">"content/repositories/snapshots"</span>)
  <span class="hljs-keyword">else</span> <span class="hljs-type">Some</span>(<span class="hljs-string">"releases"</span> at nexus + <span class="hljs-string">"service/local/staging/deploy/maven2"</span>)
}

<span class="hljs-type">ThisBuild</span> / publishMavenStyle := <span class="hljs-literal">true</span>

<span class="hljs-type">ThisBuild</span> / versionScheme := <span class="hljs-type">Some</span>(<span class="hljs-string">"early-semver"</span>)
</code></pre>
<p>You can set the <code>licenses</code> to whatever you feel is appropriate. Here is GitHub's guide to <a href="https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/licensing-a-repository">choosing a license for your repo</a> -- though be aware that they <a href="https://news.ycombinator.com/item?id=27736650">probably ignore it</a> anyway.</p>
<blockquote>
<p>❗ <strong>GOTCHA:</strong> Notice that we've also used <code>s01.oss.sonatype.org</code> above!</p>
</blockquote>
<h3>6. Publish!</h3>
<p>Once you've got all of that set up, you should be able to publish your project from the <code>sbt</code> shell with the <code>publishSigned</code> command</p>
<pre><code class="hljs language-scala">sbt> publishSigned
</code></pre>
<p>On macOS, this should open up the GPGTools UI, where you can enter the password you associated with your PGP key. The output will then look something like</p>
<pre><code class="hljs language-bash">[info] Wrote /local/path/to/zepto_2.13-0.4.0.pom
[info] 	published zepto_2.13 to https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/io/github/awwsmm/zepto_2.13/0.4.0/zepto_2.13-0.4.0-sources.jar
[info] 	published zepto_2.13 to https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/io/github/awwsmm/zepto_2.13/0.4.0/zepto_2.13-0.4.0-javadoc.jar
[info] 	published zepto_2.13 to https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/io/github/awwsmm/zepto_2.13/0.4.0/zepto_2.13-0.4.0-javadoc.jar.asc
...
</code></pre>
<p>You can use your Sonatype username and password to log in to <a href="https://s01.oss.sonatype.org/">https://s01.oss.sonatype.org/</a> where you should now see your (pre-release) project!</p>
<p>Note that if you try to click on one of the <code>.jar</code> links above, you may get an error like</p>
<pre><code>Staging of Repository within profile ID='...' is not yet started!
</code></pre>
<p>You can <a href="https://central.sonatype.org/publish/release/">follow along with Sonatype's guide here</a> to release the artifacts to the public.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ue4pc8kh7bmewm41qndl.png" alt="Screenshot of my pre-release project listed in my account on sonatype.org"></p>
<p>Select the project, click <code>Close</code> from the menu, and then <code>Release</code>. You should see your project <a href="https://repo1.maven.org/maven2/io/github/awwsmm/zepto_2.13/0.4.0/">on Maven</a> almost immediately, though it will take a few hours to show up <a href="https://search.maven.org/artifact/io.github.awwsmm/zepto_2.13">in the search engine</a>.</p>
<p>...and that's it!</p>
<p>You should now be able to import your published library into other projects by adding</p>
<pre><code>"io.github.awwsmm" %% "zepto" % "0.4.0"
</code></pre>
<p>(or whatever is appropriate) to the <code>libraryDependencies</code> in the <code>build.sbt</code> of another project.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[20 Intriguing, Unusual, and Goofy Programming Languages]]></title>
            <link>https://awwsmm.com/blog/20-intriguing-unusual-and-goofy-programming-languages</link>
            <guid isPermaLink="false">20-intriguing-unusual-and-goofy-programming-languages</guid>
            <pubDate>Sat, 16 Nov 2019 00:00:00 GMT</pubDate>
            <description><![CDATA[A collection of esoteric and thought-provoking programming languages.]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><blockquote>
<p>Originally posted on <a href="https://dev.to/awwsmm/20-intriguing-unusual-and-goofy-programming-languages-238f">Dev.To</a></p>
</blockquote>
<blockquote>
<p><em>"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"</em></p>
<p>-- <a href="http://www.jabberwocky.com/carroll/jabber/jabberwocky.html">Lewis Carroll</a></p>
</blockquote>
<hr>
<p>Despite how it can feel sometimes, programming languages are usually designed to make our lives easier. Expressing complex relationships between classes, bounds-checking data, and interacting with the user is much easier in Java than it is in <a href="https://en.wikipedia.org/wiki/Opcode">CPU opcodes</a>, for instance (and only slightly less verbose).</p>
<p>But some language designers have other goals in mind. A programming language might be designed for easy vectorisation of data, or easy multithreading, or performance. And some are designed so that the only keyword is <code>chicken</code>. <a href="https://www.youtube.com/watch?v=Qw9oX-kZ_9k">Different strokes.</a></p>
<p>Below is my curated list of 20 interesting, beautiful, and disorienting programming languages. Most of these are considered <a href="https://en.wikipedia.org/wiki/Esoteric_programming_language">"esoteric"</a> though some of them are actually used by serious programmers on a regular basis. See if you can tell which are which.</p>
<hr>
<p><a name="toc"></a></p>
<h2>Table of Contents</h2>
<ol>
<li><a href="#brainfuck">brainfuck</a></li>
<li><a href="#chicken">chicken</a></li>
<li><a href="#legit">legit</a></li>
<li><a href="#malbolge">Malbolge</a></li>
<li><a href="#apl">APL</a></li>
<li><a href="#velato">(D♭, D♭♭, and) Velato</a></li>
<li><a href="#piet">Piet</a></li>
<li><a href="#whitespace">Whitespace</a></li>
<li><a href="#intercal">INTERCAL</a></li>
<li><a href="#unary">Unary Except Every Zero Is Replaced with the Title of This Programming Language or, Alternately, Is Replaced with the Smallest Counter-Example to the Goldbach Conjecture. Compilers and Interpreters Only Have to Implement the Former Option</a></li>
<li><a href="#seed">Seed (and Befunge)</a></li>
<li><a href="#lisp">LISP</a></li>
<li><a href="#funciton">Funciton</a></li>
<li><a href="#slashes">///</a></li>
<li><a href="#factory">Factory</a></li>
<li><a href="#golf">golfing languages</a></li>
<li><a href="#2d">languages with 2-dimensional source code</a></li>
<li><a href="#aesthetics">languages which emphasise source code aesthetics</a></li>
<li><a href="#imitation">languages built so that the source code looks like ___</a></li>
<li><a href="#qsharp">Q#</a></li>
</ol>
<hr>
<p><a name="brainfuck"></a></p>
<h2>#1. <a href="https://esolangs.org/wiki/Brainfuck">brainfuck</a></h2>
<blockquote>
<p><a href="https://copy.sh/brainfuck/">online interpreter</a></p>
</blockquote>
<blockquote>
<p><em><strong>Related:</strong> <a href="https://esolangs.org/wiki/Unibrain">Unibrain</a></em></p>
</blockquote>
<p>Brainfuck (sometimes styled brainf___, brainf***, or just BF) is the poster child for esoteric programming languages (<strong>esolangs</strong>). A program which prints "hello world" in BF looks like:</p>
<pre><code class="hljs language-bf"><span class="hljs-literal">+</span><span class="hljs-title">[</span><span class="hljs-literal">-</span><span class="hljs-title">[</span>&#x3C;&#x3C;<span class="hljs-title">[</span><span class="hljs-literal">+</span><span class="hljs-title">[</span><span class="hljs-literal">---</span>><span class="hljs-title">]</span><span class="hljs-literal">-</span><span class="hljs-title">[</span>&#x3C;&#x3C;&#x3C;<span class="hljs-title">]</span><span class="hljs-title">]</span><span class="hljs-title">]</span>>>><span class="hljs-literal">-</span><span class="hljs-title">]</span>><span class="hljs-literal">-</span><span class="hljs-string">.</span><span class="hljs-literal">---</span><span class="hljs-string">.</span>><span class="hljs-string">.</span><span class="hljs-string">.</span>><span class="hljs-string">.</span>&#x3C;&#x3C;&#x3C;&#x3C;<span class="hljs-literal">-</span><span class="hljs-string">.</span>&#x3C;<span class="hljs-literal">+</span><span class="hljs-string">.</span>>>>>><span class="hljs-string">.</span>><span class="hljs-string">.</span>&#x3C;&#x3C;<span class="hljs-string">.</span>&#x3C;<span class="hljs-literal">-</span><span class="hljs-string">.</span>
</code></pre>
<p>Brainfuck is a <strong>tape-based</strong> language. You can imagine a program in a tape-based language as an extremely long, one-dimensional array of (initially) zeros. There is a pointer, which is initially at one end of the tape and can be moved forward or backward, one memory cell at a time. The values in cells can be incremented or decremented (restricting them to integer values), and there are brackets which allow for loops.</p>
<p>There are eight commands in the BF language specification. The cell to which the pointer is currently pointing is referred to as the "current cell":</p>
<pre><code>>  move the pointer one cell to the right
&#x3C;  move the pointer one cell to the left
+  increment the value in the current cell
-  decrement the value in the current cell
.  output the character represented by the value in this cell
,  input a character and store it in the cell at the pointer
[  jump past the next ] if the cell under the pointer is zero
]  jump back to the most recent [ if the cell under the pointer is nonzero
</code></pre>
<p>That's it! Any other character which appears in a brainfuck program is assumed to be a comment and is ignored. Brainfuck is <a href="https://en.wikipedia.org/wiki/Turing_completeness">Turing complete</a> and so, theoretically, it can perform any computational task that any other programming language can, though it might take a bit more time to program it in BF.</p>
<p>Brainfuck has inspired countless imitator languages, including:</p>
<ul>
<li><a href="https://esolangs.org/wiki/(_%CD%A1%C2%B0_%CD%9C%CA%96_%CD%A1%C2%B0)fuck"><strong>( ͡° ͜ʖ ͡°)fuck</strong></a> -- similar to brainfuck, but the commands are all replaced by <a href="https://en.wikipedia.org/wiki/List_of_emoticons#Lenny_Face">Lenny faces</a></li>
<li><strong><a href="https://vimeo.com/7133810">Bodyfuck</a></strong> -- a gestural interpreter for brainfuck</li>
<li><strong><a href="https://esolangs.org/wiki/I_hate_your_bf-derivative_really_I_do">I hate your bf-derivative really I do</a></strong> -- a language with the same character set as BF, but where all of the characters have different meanings; designed to frustrate BF enthusiasts</li>
<li><strong><a href="https://esolangs.org/wiki/JSFuck">JSFuck</a></strong> -- an "esoteric subset" of JavaScript, which only uses the characters <code>+</code>, <code>!</code>, <code>(</code>, <code>)</code>, <code>[</code>, <code>]</code>, creating a BF-like syntax in which a "Hello, World!" program requires more than 10,000 source code characters</li>
<li><strong><a href="https://esolangs.org/wiki/Treehugger">TreeHugger</a></strong> -- a derivative of BF which uses an infinite binary tree data structure, rather than an infinite tape</li>
<li><strong><a href="https://esolangs.org/wiki/POGAACK">POGAACK</a></strong> -- a BF / Chicken crossover</li>
</ul>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="chicken"></a></p>
<h2>#2. <a href="https://esolangs.org/wiki/Chicken">chicken</a></h2>
<p>Chicken is probably the best known <strong>single-keyword</strong> language, even though, technically, there are eleven instructions in the stack-based Chicken language, which correspond to eleven <em>opcodes</em>, numbered 0 through 10.</p>
<blockquote>
<p>Chicken was inspired by <a href="https://isotropic.org/papers/chicken.pdf">a paper</a> written by Doug Zongker to poke fun at <a href="https://www.wired.com/2007/05/post-1/">unintelligible academic presentations</a>.</p>
</blockquote>
<p>The opcode number gives the number of times (given by <code>#</code> in the below table) that the <code>chicken</code> keyword must appear (separated by spaces) in order to represent that specific instruction:</p>
<table>
<thead>
<tr>
<th align="left">#</th>
<th align="left">command</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left">0</td>
<td align="left">stop execution</td>
</tr>
<tr>
<td align="left">1</td>
<td align="left">push the string "chicken" onto the stack</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">add the top two values from the stack</td>
</tr>
<tr>
<td align="left">3</td>
<td align="left">subtract the top two values from the stack</td>
</tr>
<tr>
<td align="left">4</td>
<td align="left">multiply the top two values from the stack</td>
</tr>
<tr>
<td align="left">5</td>
<td align="left">compare the top two values from the stack for equality, push a "truthy" or "falsy" result onto the stack</td>
</tr>
<tr>
<td align="left">6</td>
<td align="left">double wide instruction. Next instruction indicates source to load from. 0 loads from stack, 1 loads from user input. Top of stack points to address/index to load onto stack.</td>
</tr>
<tr>
<td align="left">7</td>
<td align="left">top of stack points to address/index to store to. The value below that will be popped and stored.</td>
</tr>
<tr>
<td align="left">8</td>
<td align="left">the top of stack is a relative offset to jump to. The value below that is the condition. Jump only happens if condition is truthy.</td>
</tr>
<tr>
<td align="left">9</td>
<td align="left">interprets the top value on the stack as ASCII and pushes the corresponding character</td>
</tr>
<tr>
<td align="left">10+n</td>
<td align="left">pushes the literal number <code>n-10</code> onto the stack.</td>
</tr>
</tbody>
</table>
<p>When the program stops, whatever happens to be on the stack is printed to the screen (this is common in languages designed for <a href="https://en.wikipedia.org/wiki/Code_golf">code golfing</a>). This means that a <a href="https://en.wikipedia.org/wiki/Quine_(computing)">self-replicating <em>quine</em> program</a> is quite easy to create in the language:</p>
<pre><code>chicken
</code></pre>
<p>As the keyword <code>chicken</code> appears once in the first line, the string "chicken" is pushed onto the stack. The end of the program is then reached and the stack (which contains only the word "chicken") is printed to the screen. The program has reproduced its own source code exactly. This is quite difficult to do in most languages, though Mame (given name Yusuke Endoh) has created <a href="https://github.com/mame/quine-relay">this absolutely bonkers <em>quine relay</em></a>, which cycles through 100 different programming languages, each outputting the source code of the next one. (Seriously, <a href="https://github.com/mame">go check out some of their projects on GitHub</a>, they're nuts.)</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="legit"></a></p>
<h2>#3. <a href="https://morr.cc/legit/">legit</a></h2>
<blockquote>
<p><em><strong>Related:</strong> <a href="https://esolangs.org/wiki/Dirst">Dirst</a></em></p>
</blockquote>
<p>Legit (pronounced with a hard "g") is a Turing-complete programming language where programs "are defined entirely by the graph of commits in a <a href="https://www.git-scm.com/">Git</a> repository." The content of the repository itself is completely ignored.</p>
<p>Legit instructions are encoded in the commit messages in a Git repo. Execution proceeds normally from a commit to its parent (moving <em>down</em> the output of a <code>git log --graph --oneline</code> command). If a commit has multiple parents, they form a stack of commands, indexed from 0 (the eldest commit), the top of the stack is popped and value must be a number corresponding to the proper parent index. Program flow can be controlled, though, with <code>goto</code>-like commands that can jump to particular commits.</p>
<p>A <a href="https://github.com/blinry/legit-hello">"Hello World!" program in legit</a> looks like:</p>
<pre><code>$ git log --graph --oneline
*   b63fd70 (HEAD -> master, origin/master, origin/HEAD) Merge pull request #1 from rohieb/master
|\  
| *   1f44c51 0
| |\  
| |/  
|/|   
* | b9e1e95 "Hello world\n"
| * fbb02fe "Hello world!\n"
|/  
*   8013037 (tag: reverse-loop) dup
|\  
| * 6883822 write 1 left [reverse-loop]
*   e0a4d04 (tag: print-loop) 1 right read dup
|\  
| * d646ef4 put [print-loop]
* 25a3a62 quit
</code></pre>
<p>Notice that there are two lines which say "Hello World", and the second one has a "!" added at the end. The creator of the language made this program, then merged a PR for that change. Since legit programs are themselves Git repositories, there's <em>no such thing as version control</em> with a legit program, at least version control with Git itself. This means programs can end up looking messy as changes are made.</p>
<p>The language creator, Sebastian Morr, has discussed how difficult it can be to write legit programs:</p>
<blockquote>
<p><em>"I’ll be honest with you: I got tired of writing Git commands by hand to create legit programs. One consequence of the execution going top-down is that you have to write your programs backwards, and each time I’d make a typo, I’d have to start all over, because the commits above that would be invalidated. So… I started to write shell scripts, which would then generate my legit programs."</em></p>
</blockquote>
<p>In spite of this, he's managed to write <a href="https://github.com/blinry/legit-brainfuck">a brainfuck interpreter in legit</a>, indirectly showing that legit is Turing complete. Morr's challenge to users of his language? <em>Write a legit quine:</em></p>
<blockquote>
<p><em>"Write a legit program that prints the Git commands required to create itself! Good luck."</em></p>
</blockquote>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="malbolge"></a></p>
<h2>#4. <a href="https://en.wikipedia.org/wiki/Malbolge">Malbolge</a></h2>
<blockquote>
<p><a href="http://www.malbolge.doleczek.pl/">online interpreter</a></p>
</blockquote>
<p>Named after <a href="http://www.fullbooks.com/Dante-s-Inferno8.html">the eighth circle of Hell</a> from Dante's <em>Inferno</em>, Malbolge is a language specifically designed to be nearly impossible to use. Malbolge programs use base-3 arithmetic (so there are <em>tritwise</em> operations instead of <em>bitwise</em> ones), alter and encrypt their own source code, and are actively sabotaged by bug-features in the implementation and specification.</p>
<p>The creator of Malbolge, Ben Olmstead, says that <a href="https://esoteric.codes/blog/interview-with-ben-olmstead">if he could make the language more difficult to code in, he would</a>:</p>
<blockquote>
<p><em>"I know there is a mismatch between the documented and implemented tables.  I have noticed that some people decide that the bug is in the specification, and others decide the bug is in the implementation; it certainly makes Malbolge harder to use, and fragments the user community (such as it is)."</em></p>
<p><em>"If I were to make a Malbolge 2000, I would definitely make <a href="http://www.lscheffer.com/malbolge.shtml">the documentation</a> subtly wrong."</em></p>
</blockquote>
<p>Malbolge is so difficult to write in, that even Olmstead has never written a program in it, beyond "a program that printed 'H' and exited". The first "Hello, World!" for Malbolge wasn't <em>written</em>, it was <a href="http://acooke.org/malbolge.html"><em>discovered</em> eight years after the language was released</a> by a <a href="https://en.wikipedia.org/wiki/Beam_search">beam search</a> algorithm, exploring the space of all possible Malbolge programs until one was found to produce the correct output.</p>
<p>Here's a sample "Hello World!" program in Malbolge:</p>
<pre><code>(=&#x3C;`#9]~6ZY32Vx/4Rs+0No-&#x26;Jk)"Fh}|Bcy?`=*z]Kw%oG4UUS0/@-ejc(:'8dc
</code></pre>
<p>Ryan Kusnery, collector of weird languages, has declared that "the day that someone writes, in Malbolge, a program that simply copies its input to its output, is the day my hair spontaneously turns green. It's the day that elephants are purple and camels fly, and a cow can fit through a needle's eye."</p>
<p>Despite Kusnery's certainty about the impossibility of such a program, professional esoteric programmer Matthias Lutter has managed to write <a href="https://lutter.cc/malbolge/quine.html">a Malbolge quine</a>, which, though coming in at 800+ lines, does manage to exactly output its source code (<a href="http://www.malbolge.doleczek.pl/">try it out here</a> if you've got about an hour to waste).</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="apl"></a></p>
<h2>#5. <a href="https://en.wikipedia.org/wiki/APL_(programming_language)">APL</a></h2>
<p>I think A Programming Language (APL) is one of the most impressive esoteric languages (if you can call it that) I've ever encountered, mainly because it existed decades before most other languages on this list.</p>
<blockquote>
<p>The only other major languages around at the time of APL were  <a href="https://en.wikipedia.org/wiki/COBOL#Scope_termination">COBOL</a>, <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)#Examples">LISP</a>, <a href="https://en.wikipedia.org/wiki/Fortran#Simple_FORTRAN_II_program">FORTRAN</a>, and <a href="https://en.wikipedia.org/wiki/ALGOL#Code_sample_comparisons">ALGOL</a>, the spiritual precursor to the C family of languages.</p>
</blockquote>
<p>APL was <a href="https://en.wikipedia.org/wiki/APL_(programming_language)">created by Kenneth Iverson in the early 1960s</a> with a primary goal of providing easy, concise manipulation of arrays, matrices, and higher-dimensional data structures. Matrix manipulation is common in mathematics, physics, and computation-heavy sciences. Providing an easy way to create and manipulate these data structures should make these scientists' lives easier. Theoretically.</p>
<p>Manipulation of multi-dimensional arrays is of course still critical to these fields, so modern languages like <a href="https://en.wikipedia.org/wiki/APL_(programming_language)#Derivative_languages">MATLAB, Wolfram Language, and R</a> have drawn much inspiration from APL. The biggest difference between these more modern languages and APL is APL's character set.</p>
<p>In an ALGOL-like (C-like) language, you might define an array of numbers like:</p>
<pre><code class="hljs language-C">int array[] = { 1, 2, 3, 4, 5, 6 };
</code></pre>
<p>In APL, this looks like</p>
<pre><code>array ← ⍳6
</code></pre>
<p>The leftwards-pointing arrow <code>←</code> is used for assignment, and the iota character <code>⍳</code> is used to create an array of integers from <code>1</code> to <code>N</code>, where <code>N</code> is the number which follows the <code>⍳</code> character.</p>
<p>APL introduces a wide variety of uncommon characters which perform different functions. This has the effect of keeping the code itself very compact, often at the cost of readability (for the programmer accustomed to languages like ALGOL, FORTRAN, COBOL, or LISP). The following C code:</p>
<pre><code class="hljs language-C">int arr[] = { 4, 5, 6, 7 };
int len = sizeof(arr)/sizeof(arr[0]);
int sum = 0;

for (int ii = 0; ii &#x3C; len; ++ii)
  sum += arr[ii];
</code></pre>
<p>...can be compressed dramatically with APL:</p>
<pre><code>sum ← +/(3+⍳4)
</code></pre>
<p>APL uses <em>vectorised</em> operations to add <code>3</code> to every element of the array created by <code>⍳4</code>. <code>⍳4</code> creates the array <code>[1, 2, 3, 4]</code>, and <code>3+⍳4</code> adds <code>3</code> to each element of that array, to get <code>[4, 5, 6, 7]</code>. Then, the "sum over" operator <code>+/</code> sums the elements of that array <code>4 + 5 + 6 + 7</code> to get <code>22</code>, which is then assigned to <code>sum</code> via the leftward-pointing arrow.</p>
<p>I hope this explanation has given you just a small taste of what APL is capable of. Some modern languages like R make heavy use of vectorised operations, which can make manipulation of data very easy and concise, but it does take some getting used to.</p>
<p>Masters of APL can write incredibly complex programs using only a few dozen characters (though many of these are APL-specific characters). <a href="https://en.wikipedia.org/wiki/APL_(programming_language)#Game_of_Life">For your enjoyment / confusion</a>, here is the entirety of <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">John Conway's Game of Life</a>, written in <a href="https://en.wikipedia.org/wiki/APL_(programming_language)#Dyalog_APL">Dyalog APL</a>, a modern dialect of the language:</p>
<pre><code>life ← {↑1 ⍵∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵}
</code></pre>
<p>If anyone can explain that to me in the comments, step-by-step, I would be extremely impressed.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="velato"></a></p>
<h2>#6. (D♭, D♭♭, and) Velato</h2>
<blockquote>
<p><em><strong>Related:</strong> <a href="https://web.archive.org/web/20160131122814/http://www.stephensykes.com/choon/choon.html">Choon</a>, <a href="https://esolangs.org/wiki/Musical_notes">Musical Notes</a></em></p>
</blockquote>
<p><a href="https://esolangs.org/wiki/D%E2%99%AD"><strong>D♭</strong></a> (pronounced "dee flat", like the musical note) and <a href="https://esolangs.org/wiki/D%E2%99%AD%E2%99%AD">D♭♭</a> ("dee double flat") are <a href="https://esolangs.org/wiki/Joke_language_list">joke languages</a>, never actually implemented as far as I can tell. Which is unfortunate, because D♭ was supposed to offer "<em>minor</em> but <em>key</em> improvement[s]" to the C# language, including:</p>
<ul>
<li>
<p><code>LowerClass</code>, <code>MiddleClass</code> and <code>UpperClass</code> objects, which are distinguished according to the properties they can have and their permitted interactions with the other <code>Class</code>es. <code>UpperClass</code> entities can become <code>friends</code> via the <code>Lobby</code>, for instance:</p>
<pre><code>UpperClass BigShotRepublican
{
  Investments portfolio;
  Yacht coasts[6];
  Lobby&#x3C;Politicians> inPocket;
}
</code></pre>
</li>
<li>
<p>More "visually intuitive" exception handling, with the addition of new keywords <code>throwUp</code>, <code>upChuck</code>, <code>puke</code>, <code>ralph</code>, and <code>hurl</code>. As the language documentation notes:</p>
<blockquote>
<p>These convey different levels of exception severity and can be used by your application to determine the size of the <code>bucket</code> needed to catch the exception... Sometimes the <code>bucket</code> can overflow, so you'll need to stack <code>bucket</code>s so they catch the overflow.</p>
</blockquote>
</li>
<li>
<p>New <em>generics</em>, including <code>Hash</code>, <code>Pot</code>, <code>Coke</code>, and <code>Crystal</code>. According to the documentation, "[a]ll the generics are handled in the <code>StreetCorner.Pharmacy</code> namespace" and can "accelerate the performance of your application" and "enhance your end-user experience", but should be used in moderation.</p>
</li>
</ul>
<p>While D♭ would have offered these (and more) improvements on the C# language, <strong>D♭♭</strong> would have provided similar benefits (presumably) over the C language.</p>
<p><a href="http://velato.net/"><strong>Velato</strong></a> is another musical language, though it differs from D♭ and D♭♭ in that it's actually been implemented. Velato source code is written in <a href="https://en.wikipedia.org/wiki/MIDI">MIDI</a> files -- the pitch and ordering of notes determines the action of the program.</p>
<p>The first note of the program is the "root note", which can be changed by playing the note a major second interval from the root note. Other intervals and grouping of notes determine other operations; for example, the modulus operator <code>%</code> is encoded by playing the fifth, then the fifth again, then the sixth of the root note.</p>
<p>A sample "Hello, World!" program in Velato might look like:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/vfh67pcfht42wc12v270.gif" alt="&#x22;Hello, World!&#x22; in Velato"></p>
<blockquote>
<p><a href="https://www.youtube.com/watch?v=Fhni-6Q5z80">Listen here!</a></p>
</blockquote>
<p>Though the ordering of concurrent ("stacked") notes does affect the operation of the program, so sheet music alone can't fully describe a Velato program.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="piet"></a></p>
<h2>#7. <a href="https://esolangs.org/wiki/Piet">Piet</a></h2>
<blockquote>
<p><em><strong>Related:</strong> <a href="https://esolangs.org/wiki/Skastic">Skastic</a></em></p>
</blockquote>
<p>Another <em>artistic</em> esoteric language is Piet, named after the Dutch painter <a href="https://en.wikipedia.org/wiki/Piet_Mondrian">Piet Mondrian</a>, famous for his abstract art, composed of simple geometric shapes:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/vj6tzyratvcqhllembfr.jpg" alt="Piet Mondrian&#x27;s 1930 work of art, &#x22;Composition II in Red, Blue, and_Yellow&#x22;"></p>
<p><a href="http://www.dangermouse.net/esoteric/piet.html">Piet programs are "written"</a> as pixels in bitmap files, in 3 different shades of 6 different hues, plus white and black, for a total of 20 different colors. The "colorful" colors (all but white and black) are <a href="http://homepages.vub.ac.be/~diddesen/piet/index.html">arranged in a torus</a>, where moving from the base hue to its "dark" hue to its "light" hue and back to the base hue is all considered movement in the same (positive) direction. Similarly, movement from red -> yellow -> green -> cyan -> blue -> magenta -> red -> ... is cyclical and directed (positive), as well.</p>
<p>When the program starts, Piet "reads" the colors of the pixels in the bitmap, starting in the top-left corner of the image. Execution proceeds from the left to the right until a "wall" of black pixels is encountered, at which point, the direction of program execution changes and pixels are read from top-to bottom (always changing direction by rotating by 90 degrees clockwise). The edges of the canvas are considered "black pixels", as well.</p>
<p>The transitions between colored areas encode the action of the program. For instance, if we "rotate" the hue by one unit (e.g. from red -> yellow) as we move along the image, that encodes an "add" action. If we also change the "lightness" by one unit (e.g. from red -> dark yellow), that encodes a "subtract" action. Movement into or out of a white area encodes no action, and is the only way to change the color without performing an action (this is useful for loops).</p>
<p>Because the program only depends on transitions between colors, and not the colors themselves, or the direction of movement across the "canvas", programs can be very simple or very "artistic". For example, <a href="https://web.archive.org/web/20191119023906/http://homepages.vub.ac.be/~diddesen/piet/index.html">here's a program which gets a number from the user, squares it, then prints the square</a>:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/i77oznhfqnyu147wxesz.png" alt="A simple program in Piet"></p>
<p>...and here's that same program, <a href="https://www.merriam-webster.com/words-at-play/zhuzh-zhoosh-queer-eye-origin-kressley"><em>zhuzhed</em></a> up a bit:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/1clwo2qss6zurm2kisdw.png" alt="That same program, made to look a bit nicer"></p>
<p>One of the nicest Piet programs I've seen is <a href="https://en.wikipedia.org/wiki/Esoteric_programming_language#Piet">this one, which prints "Piet"</a>:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/4auzkqsxjc8aclmgi171.gif" alt="A very nice-looking program in Piet"></p>
<p>Now we just need someone to combine Piet and Velato and create a language where programs are encoded within multimedia files.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="whitespace"></a></p>
<h2>#8. <a href="https://en.wikipedia.org/wiki/Whitespace_(programming_language)">Whitespace</a></h2>
<blockquote>
<p><em><strong>Related:</strong> <a href="http://blogs.perl.org/users/zoffix_znet/2016/05/anguish-invisible-programming-language-and-invisible-data-theft.html">Anguish</a></em></p>
</blockquote>
<p>The importance of whitespace characters (spaces, line breaks, tabs, etc.) in a programming language exists on a spectrum. Some languages don't care very much, <a href="https://en.wikipedia.org/wiki/Off-side_rule">some care quite a lot</a> (see: Python), and at least one language <em>only</em> cares about whitespace characters. That language is called -- creatively enough -- Whitespace.</p>
<p>All visible characters (digits, letters, punctuation, etc.) are ignored by Whitespace. In fact, most whitespace characters are actually ignored by Whitespace, too. The <a href="https://hackage.haskell.org/package/whitespace-0.4/src/docs/tutorial.html">space (ASCII 32), tab (ASCII 9) and line feed (ASCII 10) characters</a> are the only characters which carry any meaning in a Whitespace program.</p>
<p>A "Hello, world!" program in Whitespace looks like this ("dots" <code>.</code> added to the end of each line so "trailing whitespace" is not removed in this browser):</p>
<pre><code>   	  	   .
	.
     		  	 	.
	.
     		 		  .
	.
     		 		  .
	.
     		 				.
	.
     	 		  .
	.
     	     .
	.
     	 	 			.
	.
     		 				.
	.
     			  	 .
	.
     		 		  .
	.
     		  	  .
	.
     	    	.
	.
  .


</code></pre>
<p>(You can click and drag to highlight the spaces and tabs in the code above. Or try it out in <a href="https://vii5ard.github.io/whitespace/">this web REPL</a>.)</p>
<p>Whitespace code is written one command at a time, where a particular sequence of tabs, spaces, and line feeds indicates a certain category of commands -- I/O, stack manipulation, arithmetic. Once the category is selected, the particular command in that category is selected with another sequence of tabs, spaces, and line feeds. All numbers are binary encoded (space = 0, tab = 1) and all characters are indicated by their ASCII indices (again, binary encoded, so tab-space-space-space-space-tab-tab is <code>1000011</code> or <code>67</code> or <code>C</code>).</p>
<p>All sorts of programs have been written in Whitespace, including <a href="https://github.com/vii5ard/whitespace/blob/master/example/quine.ws">quines</a>, <a href="https://github.com/vii5ard/brainfuck-whitespace">Brainfuck interpreters</a>, and more. And some Whitespace programs have surely been hidden in the source code for other languages. These <em>polyglot</em> programs could be run as Whitespace code -- where all the visible characters are ignored -- or as code in the "host" language, provided the whitespace needed for the hidden Whitespace program is not significant.</p>
<p>Just in case you needed another thing to worry about.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="intercal"></a></p>
<h2>#9. <a href="https://en.wikipedia.org/wiki/INTERCAL">INTERCAL</a></h2>
<p>INTERCAL, short for <em>Compiler Language With No Pronounceable Acronym</em>, is arguably the first-ever esoteric language.</p>
<blockquote>
<p><em>"...created as a parody by Don Woods and James M. Lyon, two Princeton University students, in 1972...[INTERCAL] satirizes aspects of the various programming languages at the time, as well as the proliferation of proposed language constructs and notations in the 1960s."</em> <a href="https://en.wikipedia.org/wiki/INTERCAL">[ source ]</a></p>
</blockquote>
<p>INTERCAL is designed to be confusing and difficult to work with. Common symbols are pointlessly renamed (<code>'</code> is a "spark", <code>"</code> is "rabbit ears", <code>:</code> is a "twospot", ...), numbers can only be given as input by spelling out the digits one at a time (<code>TWO FIVE SIX</code> is the number <code>256</code>), and an undocumented "feature" means that programs can be rejected by the compiler for not being polite (not using the keyword <code>PLEASE</code> enough) -- or for being overly polite (using <code>PLEASE</code> too much).</p>
<p><a href="https://en.wikipedia.org/wiki/INTERCAL#Details">Wikipedia offers this <em>amazing</em> quote</a> from the INTERCAL reference manual</p>
<blockquote>
<p>It is a well-known and oft-demonstrated fact that a person whose work is incomprehensible is held in high esteem. For example, if one were to state that the simplest way to store a value of 65536 in a 32-bit INTERCAL variable is:</p>
</blockquote>
<pre><code>DO :1 &#x3C;- #0¢#256
</code></pre>
<blockquote>
<p>any sensible programmer would say that that was absurd. Since this is indeed the simplest method, the programmer would be made to look foolish in front of his boss, who would of course happen to turn up, as bosses are wont to do. The effect would be no less devastating for the programmer having been correct.</p>
</blockquote>
<p>INTERCAL is a very forgiving language, though. Anything the INTERCAL compiler -- <code>ick</code> -- can't understand is simply ignored. This means that all INTERCAL programs are by definition bug-free! Which is good, because the original INTERCAL was written for the <a href="https://en.wikipedia.org/wiki/EBCDIC">EBCDIC</a> character set, but latter versions moved to ASCII. As a result, different dialects of INTERCAL have totally different instruction sets.</p>
<p>And for the fifteen people on the planet who want to get INTERCAL working with .NET, you're in luck -- <a href="https://github.com/jawhitti/INTERCAL">someone's had enough free time to make that a reality</a>.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="unary"></a></p>
<h2>#10. <a href="https://esolangs.org/wiki/Unary_Except_Every_Zero_Is_Replaced_with_the_Title_of_This_Programming_Language_or,_Alternately,_Is_Replaced_with_the_Smallest_Counter-Example_to_the_Goldbach_Conjecture._Compilers_and_Interpreters_Only_Have_to_Implement_the_Former_Option">Unary Except Every Zero Is Replaced with the Title of This Programming Language or, Alternately, Is Replaced with the Smallest Counter-Example to the Goldbach Conjecture. Compilers and Interpreters Only Have to Implement the Former Option</a></h2>
<p>In the section on <a href="#brainfuck">brainfuck</a>, above, we saw just a tiny sample of the <em>hundreds</em> of BF-derivative languages that exist. While there are some interesting derivative languages, I tried my best not to include any of them, since this article would quickly devolve into nonsense.</p>
<p>However, there's one <em>special bit of nonsense</em> that I'd like to share with you from the brainfuck world. It's a little language called <em>Unary Except Every Zero Is Replaced with the Title of This Programming Language or, Alternately, Is Replaced with the Smallest Counter-Example to the Goldbach Conjecture. Compilers and Interpreters Only Have to Implement the Former Option</em>. (For the rest of this entry, I will refer to the aforementioned language as "this language".)</p>
<p>This language is what it sounds like, it's a derivative of the <a href="https://esolangs.org/wiki/Unary"><em>Unary</em> programming language</a>. Unary has the same commands as BF, but they're encoded in a <a href="https://en.wikipedia.org/wiki/Unary_numeral_system"><em>unary numeral system</em></a> -- that is, a system which only has a single symbol. In this case, that symbol is <code>0</code>.</p>
<blockquote>
<p>Unary systems aren't as unusual as they may sound, and you've almost certainly encountered one before. If you've ever had to track a hand-raised vote or keep track of wins and losses in a series of games, you may have used <a href="https://en.wikipedia.org/wiki/Tally_marks"><em>tallies</em></a>. In this system, a single straight line represents <code>1</code>, two single straight lines represent <code>2</code>, and so on. Tally marks are a unary numeral system.</p>
</blockquote>
<p>In Unary, brainfuck commands are encoded in binary using the following table:</p>
<table>
<thead>
<tr>
<th align="center">brainfuck command</th>
<th align="center">binary index</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">></td>
<td align="center">000</td>
</tr>
<tr>
<td align="center">&#x3C;</td>
<td align="center">001</td>
</tr>
<tr>
<td align="center">+</td>
<td align="center">010</td>
</tr>
<tr>
<td align="center">-</td>
<td align="center">011</td>
</tr>
<tr>
<td align="center">.</td>
<td align="center">100</td>
</tr>
<tr>
<td align="center">,</td>
<td align="center">101</td>
</tr>
<tr>
<td align="center">[</td>
<td align="center">110</td>
</tr>
<tr>
<td align="center">]</td>
<td align="center">111</td>
</tr>
</tbody>
</table>
<p>To write a Unary program, one starts by writing a brainfuck program. As an example, here's a very simple BF program that simply adds the number <code>2</code> to the number <code>3</code> and prints the result to the terminal:</p>
<pre><code>++>+++[&#x3C;+>-]++++++++[&#x3C;++++++>-]&#x3C;.
</code></pre>
<p>(<a href="https://copy.sh/brainfuck/">Try it out here!</a>)</p>
<p>In Unary, we first convert all of these BF symbols to their binary equivalents:</p>
<pre><code>010010000010010010110001010000011111010010010010010010010010110001010010010010010010000011111001100
</code></pre>
<p>...then, we prepend a <code>1</code> to this very large binary number:</p>
<pre><code>1010010000010010010110001010000011111010010010010010010010010110001010010010010010010000011111001100
</code></pre>
<p>...and finally, we convert this number to unary. <a href="https://www.wolframalpha.com/input/?t=crmtb01&#x26;f=ob&#x26;i=1010010000010010010110001010000011111010010010010010010010010110001010010010010010010000011111001100%20in%20decimal">Wolfram|Alpha</a> tells me that this number is equivalent to</p>
<pre><code>812,443,533,011,490,965,255,226,984,396
</code></pre>
<p>...in decimal ("about 812 octillion"), so a unary representation of this number would simply be that many <code>0</code>s, back-to-back.</p>
<p>What makes <em>this language</em> different from the Unary language is that this language then replaces each of those <code>0</code> characters with either:</p>
<ul>
<li>the title of <em>this</em> programming language, or, alternatively</li>
<li>the smallest counter-example to <a href="https://en.wikipedia.org/wiki/Goldbach%27s_conjecture">the Goldbach Conjecture</a></li>
</ul>
<p>The Goldbach Conjecture (aka. "Goldbach's Conjecture") states that</p>
<blockquote>
<p>...every even integer greater than 2 can be expressed as the sum of two primes. <a href="https://en.wikipedia.org/wiki/Goldbach%27s_conjecture">[ source ]</a></p>
</blockquote>
<p>Presumably, we would replace each <code>0</code> with that smallest integer, which (as of this writing), is bounded on the low end by at least <a href="https://en.wikipedia.org/wiki/Goldbach%27s_conjecture#Verified_results">4 * 10^18</a>. However, since Goldbach's Conjecture hasn't yet actually been disproven, we can't replace <code>0</code> with anything except the name of this programming language. Luckily, "compilers and interpreters only have to implement the former option".</p>
<p>Even so, the above <code>2+3</code> program in this language would be quite long, as the name of this programming language is 238 characters. Encoding that single small program in this language would require about <a href="https://www.wolframalpha.com/input/?t=crmtb01&#x26;f=ob&#x26;i=812%2C443%2C533%2C011%2C490%2C965%2C255%2C226%2C984%2C396+*+238+bytes+in+TB">a billion trillion terabytes</a> of disk space. This language is a strong contender for the most resource-inefficient language in the universe.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="seed"></a></p>
<h2>#11. <a href="https://esolangs.org/wiki/Seed">Seed (and Befunge)</a></h2>
<p>Seed is related to an earlier esolang named <a href="https://en.wikipedia.org/wiki/Befunge">Befunge</a>, in which programs are written on a 2-dimensional grid. In Befunge, the user defines "arrow" instructions to move pointers around the program. For example, a Befunge "Hello, World!" could be written like:</p>
<pre><code>>              v
v  ,,,,,"Hello"&#x3C;
>48*,          v
v,,,,,,"World!"&#x3C;
>25*,@
</code></pre>
<p>You can see the <code>></code> <code>v</code>, and <code>&#x3C;</code> characters, which literally point in the direction that the code should be interpreted / compiled. (There's also a <code>^</code> character which is not used here.)</p>
<p>Befunge was designed specifically to be difficult to compile. Because it can be executed in any one of four directions (left-to-right, right-to-left, top-to-bottom, or bottom-to-top), and because it provides facilities for self-modifying code, it can be extremely difficult for a compiler to reason about Befunge source code.</p>
<p>Seed takes this relatively nice (but definitely unusual) language and makes it completely ridiculous. A Seed program is only ever composed of two numbers: a length, and a random seed. The random seed is fed to a <a href="https://en.wikipedia.org/wiki/Mersenne_Twister">Mersenne Twister</a> algorithm, which is used to generate a random string of the specified length. Seed will then attempt to run that random string as a Befunge program. That's it.</p>
<p>Seed is an extremely easy language to program in -- all it requires is two numbers -- but, because of its inherent randomness, it requires huge amounts of resources. Programming in Seed usually means generating lots of random programs of a specified length and checking the program output against the desired output. As there are <a href="https://esolangs.org/wiki/Seed">96 valid characters in a Befunge program</a> (ASCII 32 through 126, plus line feed), there are <code>96^n</code> possible Befunge programs containing <code>n</code> characters. Testing all valid programs of length 5 therefore requires generating and running over 8 billion unique Befunge programs.</p>
<p>In spite of this, some enthusiasts have somehow managed to write Seed programs which actually do useful (?) things. For example, this program:</p>
<pre><code>1 186
</code></pre>
<p>...does nothing and exits, while this program:</p>
<pre><code>4 80814037
</code></pre>
<p>...prints the character <code>'h'</code>. Because the number of possible programs increases exponentially as the length of the program increases, a "Hello World" program is incredibly difficult, yet esolang enthusiast <a href="https://github.com/KrzysztofSzewczyk">Krzysztof Szewczyk</a> has still managed to find a solution with a random seed of only 4151 digits. Like I said, easy to program in!</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="lisp"></a></p>
<h2>#12. <a href="https://en.wikipedia.org/wiki/Lisp_(programming_language)">LISP</a></h2>
<p>The more I learn about LISP, the more I like it. First released in 1958, <a href="https://web.archive.org/web/20010727170154/http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-5.html">LISP is one of the oldest high-level languages</a> still in common use today (only a year younger than FORTRAN, which is still popular in the scientific community). LISP stands for LISt Processor and essentially that's what it does -- it processes lists.</p>
<p>Everything in LISP is either an <em>atom</em> or a <em>list</em>. Lists can contain atoms, as well as other lists. Atoms are "indivisible" and are things like numbers, strings, and so on. For example, the following list:</p>
<pre><code class="hljs language-lisp">(<span class="hljs-number">1</span> <span class="hljs-string">"hey"</span> (<span class="hljs-name">+</span> <span class="hljs-number">7</span> x))
</code></pre>
<p>...contains three elements: the atom <code>1</code>, the atom <code>"hey"</code>, and the list <code>(+ 7 x)</code>, which contains three elements of its own.</p>
<p>Note that there are no type declarations in LISP. The reason for this is twofold. First, LISP uses a kind of dynamic typing and can check whether an atom is a string or a number, and can provide compile-time warnings if a programmer tries to code some odd operation like dividing a number by a string. Second, LISP is such an old language that <a href="https://www.quora.com/Why-is-Lisp-dynamically-typed">type theory hadn't really yet evolved as a field of study</a> at the time the language was created. So "list" and "atom" are the only two types.</p>
<p><a href="https://www.tutorialspoint.com/lisp/lisp_input_output.htm">Here's a simple LISP program</a> (in the "Common LISP" dialect) which asks a user for a radius, and then gives the area of a circle with that radius:</p>
<pre><code class="hljs language-lisp">(<span class="hljs-name">defun</span> AreaOfCircle()
  (<span class="hljs-name">terpri</span>)
  (<span class="hljs-name">princ</span> <span class="hljs-string">"Enter Radius: "</span>)
  (<span class="hljs-name">setq</span> radius (<span class="hljs-name">read</span>))
  (<span class="hljs-name">setq</span> area (<span class="hljs-name">*</span> <span class="hljs-number">3.1416</span> radius radius))
  (<span class="hljs-name">princ</span> <span class="hljs-string">"Area: "</span>)
  (<span class="hljs-name">write</span> area)
)
(<span class="hljs-name">AreaOfCircle</span>)
</code></pre>
<p>(<a href="https://rextester.com/IDHEMA40743">Try it out here!</a>)</p>
<p>Notice how every statement in the above program is a list, including I/O and execution of various functions. LISP has the ability to manipulate lists, as well:</p>
<pre><code class="hljs language-lisp">(<span class="hljs-name">append</span> '(<span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span>) '() '(a) '(<span class="hljs-number">5</span> <span class="hljs-number">6</span>))
</code></pre>
<blockquote>
<p>Here, <a href="https://stackoverflow.com/a/1539175/2925434"><code>'x</code> is syntactic sugar for <code>(quote x...)</code></a>, which simply returns the elements <code>x...</code> without evaluating them (which is the default behaviour).</p>
</blockquote>
<p>The above list manipulates several other lists by appending them to one another, in order. The result of the above code snippet is the list:</p>
<pre><code class="hljs language-lisp">(<span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span> a <span class="hljs-number">5</span> <span class="hljs-number">6</span>)
</code></pre>
<blockquote>
<p>Note how the atom <code>a</code> hasn't been evaluated and replaced with a number or string.</p>
</blockquote>
<p>Because LISP provides methods to operate on lists, and because every LISP program is itself composed of nothing more than lists, LISP programs define data structures within the LISP language! This means that <a href="https://stackoverflow.com/a/4621882/2925434">macros</a> -- code which manipulates and runs other bits of code -- are common among LISP developers. LISP syntax defines program input, output, and the source code of the program itself. <a href="https://dev.to/awwsmm/concept-of-the-day-homoiconicity-4did">This concept, called <em>homoiconicity</em></a>, is part of what makes LISP a bit foreign to users of ALGOL-like (C-like) languages.</p>
<p>If you want to learn a cool, new (to you, at least) language in 2020, may I suggest LISP?</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="funciton"></a></p>
<h2>#13. <a href="https://esolangs.org/wiki/Funciton">Funciton</a></h2>
<p>Funciton is a programming language whose name looks like someone misspelled "function" and which I always pronounce as "funky town" in my head when I read it.</p>
<p>Funciton is a flowchart-like, two-dimensional language. A factorial function in Funciton might look like:</p>
<pre><code>                   ╓───╖
                   ║ ! ║
                   ╙─┬─╜   ┌───╖  ╔═══╗
               ┌─────┴─────┤ > ╟──╢ 2 ║
               │           ╘═╤═╝  ╚═══╝
 ╔════╗  ┌───╖ │             │
 ║ −1 ╟──┤ + ╟─┴─┐           │
 ╚════╝  ╘═╤═╝   │           │
         ┌─┴─╖   │    ╔═══╗  │
         │ ! ║   │    ║ 1 ║  │
         ╘═╤═╝   │    ╚═╤═╝  │
           │   ┌─┴─╖  ┌─┴─╖  │
           │   │ × ╟──┤ ? ╟──┘
           │   ╘═╤═╝  ╘═╤═╝
           └─────┘      │
</code></pre>
<p>Every <em>element</em> of a Funciton program is written inside of a rectangle (or "box") made of ASCII lines and double-lines. The lines between boxes carry data around the program. As Funciton programs are rotation-invariant, there are five possible kinds of boxes:</p>
<ol>
<li>double-lined on all sides: literal value OR input OR comment</li>
<li>double-lined on three sides: lambda expression</li>
<li>double-lined on two adjacent sides: function call</li>
<li>double-lined on two opposite sides: function declaration</li>
<li>double-lined on a single side: invoke a lambda function</li>
<li>double-lined on no sides: <code>NOT</code> operator (see below)</li>
</ol>
<p>If a box has no connectors, then no data can be passed to it or read from it, so that box becomes a comment:</p>
<pre><code>  ╔═════════════════════════════════════╗
  ║  Won't you take me to... Funciton?  ║
  ╚═════════════════════════════════════╝
</code></pre>
<p>A box with a single line emanating from it is either a literal or is requesting input from STDIN:</p>
<pre><code>  ╔═════════════════════════════════╗  ╔══════╗
  ║  this is the literal number 42  ║  ║  42  ╟────
  ╚═════════════════════════════════╝  ╚══════╝
  ╔════════════════════════════════╗   ╔══════╗
  ║  this box requests user input  ║   ║      ╟────
  ╚════════════════════════════════╝   ╚══════╝
</code></pre>
<p>"Rotation-invariant" means that the above <code>42</code> can be written as</p>
<pre><code>                                        │
╔══════╗        ╔══════╗  ╔══════╗  ╔═══╧══╗
║  42  ╟───  ───╢  42  ║  ║  42  ║  ║  42  ║
╚══════╝        ╚══════╝  ╚═══╤══╝  ╚══════╝
                              │
</code></pre>
<p>...and it means the same thing (a literal number <code>42</code>) in each case. Data "flows" out of boxes like this and into the "lines" connecting boxes, and "loose ends" indicate that data should be written to STDOUT. So each of the four boxes above writes <code>42</code>, converted to the character <code>*</code>, to STDOUT. (Although technically, these must be four separate programs, because an individual Funciton program can only have a single output.)</p>
<p>The lines (or "wires") aren't passive in Funciton, and T-junctions define splitters, when the input comes in as the perpendicular line of the T-junction...</p>
<pre><code>╔══════╗   │   ╔════════════════════════════════════════════╗
║  42  ╟───┤   ║  Each output line carries the value `42`.  ║
╚══════╝   │   ╚════════════════════════════════════════════╝
</code></pre>
<p>...as well as <code>NAND</code> gates, when the output is the perpendicular line:</p>
<pre><code>╔══════╗     ╔══════╗  ╔═══════════════════════════════════╗
║  42  ╟──┬──╢  25  ║  ║  Output is (42 NAND 25) or `55`.  ║
╚══════╝  │  ╚══════╝  ╚═══════════════════════════════════╝
</code></pre>
<p>Using just the splitter and the <code>NAND</code> gate, we can define <code>NOT</code>, <code>AND</code>, <code>OR</code>, and <code>XOR</code>, which allow us to then define any additional conceivable functions:</p>
<pre><code>                                                  ┌──────────────────────┐
╓─────╖        ╓─────╖            ╓────╖          │  ╓─────╖             │
║ not ║     ┌──╢ and ╟──┐      ┌──╢ or ╟──┐       ├──╢ xor ╟─────┐       │
╙──┬──╜     │  ╙─────╜  │     ┌┴┐ ╙────╜ ┌┴┐      │  ╙─────╜ ┌┐  │    ┌┐ │
   │        └─────┬─────┘     └┬┘        └┬┘      └───┬──────┤├──┴──┬─┤├─┘
  ┌┴┐            ┌┴┐           └────┬─────┘           │      └┘     │ └┘
  └┬┘            └┬┘                │                 └────┬────────┘
   │              │                                        │
</code></pre>
<p>If Funcitown sounds interesting to you, I suggest you check out <a href="https://esolangs.org/wiki/Funciton">its esolangs wiki page</a>, or, just <a href="https://esolangs.org/wiki/Funciton/99_bottles_of_beer_on_the_wall">marvel at this implementation of "99 bottles of beer"</a>, written in Funciton.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="slashes"></a></p>
<h2>#14. <a href="https://esolangs.org/wiki////">///</a></h2>
<blockquote>
<p><em><strong>Related:</strong> <a href="https://esolangs.org/wiki/Thue">Thue</a></em></p>
</blockquote>
<p>/// (pronounced "slashes") is a language where all computation is performed via <a href="https://en.wikipedia.org/wiki/Ed_(text_editor)">ed</a>-style string substitution. The only "syntax" the language has is a single construct, formed using the forward slash <code>/</code> character, which is used to define string replacements of the form:</p>
<pre><code class="hljs language-bash">/pattern/replacement/initial
</code></pre>
<p>The <code>initial</code> string is searched for the <code>pattern</code>, which is removed and replaced with the <code>replacement</code>. This search-and-replace procedure is then repeated, again, from the beginning of the new (modified) string. If the <code>pattern</code> cannot be found in the string, then the <code>initial</code> (or newly-modified) string is printed to the console and the program terminates.</p>
<p>For example:</p>
<pre><code class="hljs language-bash">/NAME/Karl Hungus/Hello, NAME!
</code></pre>
<p>The above /// program will search the string <code>Hello, NAME!</code> for the substring <code>NAME</code>, which, when found, it will replace with the string <code>Karl Hungus</code>:</p>
<pre><code class="hljs language-bash">/NAME/Karl Hungus/Hello, Karl Hungus!
</code></pre>
<p>After a single iteration, the substring <code>NAME</code> can no longer be found in the modified string, so the program terminates, printing <code>Hello, Karl Hungus!</code> to the terminal.</p>
<p>There is only a single other special character in /// and that's the backslash <code>\</code> character, which can be used to escape the <code>/</code> character as well as itself. Any program which contains no <code>/</code> or <code>\</code> characters is trivially a quine, printing its source code to the console.</p>
<p>A more difficult quine in /// is one which <em>only</em> contains the <code>\</code> and <code>/</code> characters (<a href="https://en.wikipedia.org/wiki/Leaning_toothpick_syndrome">leaning toothpick syndrome</a> to the extreme):</p>
<pre><code>/\/\/\/\\\\/\\\\\\\/\\\\\\\/\\\\\\\/\\\\\\\\\\\\\\\\\\\\\\//\/\/\/\\\/\/\\////\\////\\\///\\////\\\///\\////\\\///\\////\\\///\\\///\\\///\\\///\\////\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\////\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\////\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\////\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\////\\////\\\///\\////\\\///\\////\\\///\\////\\\///\\\///\\\///\\////\\\///\\////\\\///\\\///\\////\\////\\////\\////\\\///\\////\\\///\\////\\////\\\///\\////\\////\\\///\\////\\\///\\////\\\///\\////\\\///\\\///\\\///\\////\\\///\\\///\\\///\\////\\\///\\\///\\////\\////\\////\\////\\\///\\////\\////\\\///\\////\\////\\\///\\////\\\///\\////\\\///\\////\\\///\\\///\\\///\\\///\\////\\\///\\\///\\////\\////\\\///\\\///\\\///\\////\\\///\\\///\\\///\\////\\\///\\\///\\\///\\////\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\////\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\////\\\///\\\///\\\///\\////\\\///\\\///\\\///\\\///\\////\\////\\////\\////\\\///\\////\\////\\\///\\////\\////\\\///\\////\\\///\\////\\\///\\////\\\///\\\///\\\///\\\///\\////\\\///\\\///\\\///\\////\\\///\\\///\\\///\\////\\\///\\\///\\\///\\////\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\\///\\////\\////\\////\\////\\\///\\////\\\///\\////\\\//\/\/\/\\\/\\\/\\////\//\//\/\/\/\\\\/\\//\\\/\\\/\\\/\\\\\\\/\\\\\\\/\\\/\\\\////\//\//\/\/\/\\\\/\\\/\\\/\\\/\\\\\\\\\\////\/\/\
</code></pre>
<p>/// was indirectly shown to be Turing-Complete by <a href="https://esolangs.org/wiki/%C3%98rjan_Johansen">Ørjan Johansen</a>, who used the language to create an interpreter for a different esolang, <a href="https://esolangs.org/wiki/Bitwise_Cyclic_Tag">Bitwise Cyclic Tag</a>, which is itself Turing-Complete.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="factory"></a></p>
<h2>#15. <a href="https://esolangs.org/wiki/Factory">Factory</a></h2>
<p>Factory is a really interesting language, where your commands move a "claw" around the "byte factory". You can pick up <code>1</code>s and <code>0</code>s with the claw, move them into storage spaces, and create "shipments" of bits that are grouped into 8-bit bytes and "delivered" to the standard output as ASCII characters. Factory program files have the <code>.claw</code> extension, for obvious reasons.</p>
<p>The byte factory looks like this initially:</p>
<pre><code>     |
     |
    / \
    \ /



    [1]    | _____________ | _____________ | _____________ |    X    |   [:=:]  | [    ] | !!!!!!!! | &#x26;&#x26;&#x26; 
production |storage space 1|storage space 2|storage space 3| garbage | shipping | supply | Invertor | and
</code></pre>
<p>The different rooms have different purposes:</p>
<ul>
<li><code>production</code> creates a constant stream of <code>1</code>s at the start of the program, but can be changed to a stream of <code>0</code>s if a <code>0</code> is "dropped" into the room from the claw (dropping a <code>1</code> switches production back to a stream of <code>1</code>s)</li>
<li>the <code>storage space</code>s each hold a stack of bits. Bits dropped from the claw are added to the top of the stack and the claw can pick up the stack at any point, carrying that bit and all bits above it.</li>
<li>bits dropped into the <code>garbage</code> are destroyed and lost forever</li>
<li><code>shipping</code> works like a <code>storage space</code>, until the bits are delivered to STDOUT as ASCII characters</li>
<li><code>supply</code> receives input characters from the user, which are converted to bits and stored as a stack in reverse order (so the first bit of the first character is at the top of the stack)</li>
<li>the <code>invertor</code> accepts a single bit which it inverts (<code>0</code> becomes <code>1</code> and <code>1</code> becomes <code>0</code>)</li>
<li>the <code>and</code> room accepts two bits, destroying one of them. If either bit is a <code>0</code>, the other bit is destroyed so only a <code>0</code> remains</li>
</ul>
<p>The programmer instructs the claw to move around the factory, picking up and dropping bits and stacks of bits into the various rooms:</p>
<ul>
<li><code>&#x3C;</code> tells the claw to move left one room (if the claw is in the <code>production</code> room already, it will not move)</li>
<li><code>></code> tells the claw to move right one room (if the claw is in the <code>and</code> room already, it will not move)</li>
<li><code>v</code> tells the claw to drop all of its bits into this room, if it is carrying any, and pick up the top bit in this room otherwise</li>
<li><code>O</code> ships the contents of the shipping room</li>
<li><code>I</code> asks for an input into the supply room</li>
<li>and so on...</li>
</ul>
<p>Factory is a really neat creation that's half game, half programming language. I would love to see a Factory debugger that actually shows the claw moving around the factory, picking up bits and dropping them off in different locations. It's probably not the most useful programming language, but it's definitely unique.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="golf"></a></p>
<h2>#16. golfing languages</h2>
<p>For these next few entries, I'd like to discuss a few broader categories of languages, rather than individual languages themselves. The first category I'll start with is <a href="https://esolangs.org/wiki/Golf"><strong>golfing languages</strong></a>.</p>
<p>Golfing languages are used in <a href="https://en.wikipedia.org/wiki/Code_golf"><em>code golf</em></a>, a competition where users try to write a program with the smallest source code possible, usually measured in bytes. <a href="https://codegolf.stackexchange.com/">Code Golf Stack Exchange</a> (CGSE) is a vibrant community of programming language enthusiasts who use mainstream and esoteric languages alike. <a href="#apl">APL</a> is a common language for code golfing, though many languages were specifically created for golfing, including:</p>
<ul>
<li><a href="https://esolangs.org/wiki/GolfScript">GolfScript</a> (obviously)</li>
<li><a href="https://en.wikipedia.org/wiki/J_(programming_language)">J</a> and <a href="https://github.com/DennisMitchell/jellylanguage">Jelly</a></li>
<li><a href="https://esolangs.org/wiki/@">@</a></li>
<li><a href="https://esolangs.org/wiki/Brachylog">Brachylog</a></li>
<li><a href="https://github.com/Adriandmen/05AB1E">05AB1E</a></li>
</ul>
<p>...and many more. I've grouped J and Jelly together because the developers behind Jelly say they were influenced primarily by the J programming language, and J was designed by... <a href="https://en.wikipedia.org/wiki/J_(programming_language)">Kenneth E. Iverson</a>, creator of APL. You can find these and many more golfing languages listed on CGSE's <a href="https://codegolf.stackexchange.com/questions/44680/showcase-of-languages">Showcase of Languages</a> thread.</p>
<p>To give you a taste of what code golfing is like, here's <a href="https://codegolf.stackexchange.com/questions/110582/im-a-palindrome-are-you/">a challenge to write a program which can detect palindromes</a>, that is, strings which are read the same forwards and backwards. It doesn't matter how the program accomplishes this, but it needs to somehow indicate when input passed to it is palindromic or not. For reference, a minimal-ish palindrome-detecting program written in Java might look like:</p>
<pre><code class="hljs language-java">import java.util.*; 

public class P {
  public static void main (String a[]) {

    String o, r = "";
    Scanner s = new Scanner(System.in);

    o = s.nextLine();  

    for (int i = o.length() - 1; i >= 0; i--)
      r = r + o.charAt(i);

    System.out.println(o.equals(r));
  }
}
</code></pre>
<p>I've left whitespace in for clarity, but in a real code golf competition, we would compress this to:</p>
<pre><code class="hljs language-java">import java.util.*;public class P {public static void main(String a[]){String o,r="";Scanner s=new Scanner(System.in);o=s.nextLine();for(int i=o.length()-1;i>=0;i--)r=r+o.charAt(i);System.out.println(o.equals(r));}}
</code></pre>
<p>...and count the bytes in the solution. Since these are all ASCII characters, the number of bytes is simply the number of characters and <strong>my solution in Java has 216 bytes</strong>. How about some of these golfing languages?</p>
<p>Here's a solution in <a href="https://codegolf.stackexchange.com/a/110584/79936">Brachylog</a> (3 bytes):</p>
<pre><code>I↔I
</code></pre>
<p>...here's one in <a href="https://codegolf.stackexchange.com/a/110583/79936">Jelly</a> (5 bytes):</p>
<pre><code>ḂŒ
ŒḂ
</code></pre>
<p>...and 05AB1E (3 bytes):</p>
<pre><code>ÂQÂ
</code></pre>
<p>...J (15 bytes):</p>
<pre><code>-:|.NB. .BN.|:-
</code></pre>
<p>...GolfScript (11 bytes):</p>
<pre><code>.-1%=#=%1-.
</code></pre>
<p>...and Dyalog APL (6 bytes):</p>
<pre><code>⌽≡⊢⊢≡⌽
</code></pre>
<p>My solution suddenly looks much less impressive in comparison. You can see that most of these golfing languages use UNICODE characters extensively in their source code: a single character can encode a hugely complex operation, so using a code golf language usually means simply memorizing what lots and lots of individual characters do. If you're interested in code golfing, I recommend you check out the Code Golf Stack Exchange, or join a local in-person code golfing competition (usually, these are restricted to a single language or a pre-defined set of languages).</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="2d"></a></p>
<h2>#17. languages with 2-dimensional source code</h2>
<p>As <a href="https://www.omniglot.com/writing/direction.htm">most</a> natural, written languages are read only in one direction (in English, left-to-right) and "wrap" around the edge of a page, it's intuitive that programming languages should do the same thing. But some language designers have decided to make "better" use of the 2D space in which these languages can be written and displayed, allowing source code to be read left-to-right, top-to-bottom, or diagonally. This wider variety of reading directions has led to creations like:</p>
<ul>
<li><a href="https://esolangs.org/wiki/Hexagony">Hexagony</a></li>
<li><a href="https://esolangs.org/wiki/RunR">RunR</a></li>
<li><a href="https://esolangs.org/wiki/Re:direction">Re:direction</a></li>
<li><a href="https://esolangs.org/wiki/Beeswax">Beeswax</a></li>
<li><a href="https://esolangs.org/wiki/%E2%98%83">☃</a></li>
<li><a href="https://esolangs.org/wiki/MineFriff">MineFriff</a></li>
<li><a href="https://esolangs.org/wiki/Half-Broken_Car_in_Heavy_Traffic">Half Broken Car in Heavy Traffic</a></li>
<li><a href="https://esolangs.org/wiki/Maze">Maze</a></li>
</ul>
<p>...among others. These languages usually include constructs which change the direction in which the code should be read, much like <a href="#piet">Piet</a>'s "walls" of black pixels.</p>
<p><strong>Re:direction</strong> only uses UNICODE arrows (◄, ▲, ►, ▼) to direct program flow and add those directions to a queue, plus a single instruction for popping directions from the queue (♦), which can allow for looping and control flow. Output from the program can only be integers, but those integers can be interpreted as ASCII characters. For example, here's <a href="https://esolangs.org/wiki/Re:direction#Hello_world_program">a "Hello, World!" program</a> written in Re:direction, which you can <a href="https://tio.run/#re-direction">try out here</a>!</p>
<p>In <strong>Hexagony</strong> and <strong>Beeswax</strong>, code is written on a hexagonal grid of fixed-width characters. A "Hello, World!" program in Hexagony might look like:</p>
<pre><code>   H ; e ;
  l ; d ; *
 ; r ; o ; W
l ; ; o ; * 4
 3 3 ; @ . >
  ; 2 3 &#x3C; \
   4 ; * /
</code></pre>
<p>...and a program to print the <code>N</code>-th Fibonacci number in Beeswax might look like:</p>
<pre><code>           ;{#'&#x3C;>~P~L#MM@>+@'p@{;
 _`n`TN`F(`{`)=`X~P~K#{; d~@M&#x3C;
</code></pre>
<p>Beeswax provides additional complexity by allowing the programmer to summon "bees", which act as pointers, moving around the program in various directions and completing tasks independently of one another.</p>
<p>In <strong>Maze</strong>, the program's source code looks like... a maze:</p>
<pre><code>               ##,##,##    // fibonacci
            ##,##,^^,##,##
            ##,..,&#x3C;>,PP,##
            ##,..,##,..,##,##,##,##,##,##,##,##  // left column is fib(n), right column is fib(n+1).
##,##,##,##,##,%D,..,LD,..,**,..,..,..,..,..,##  // the small left loop sets fib(n) to 0; simultaneously,
##,..,..,..,##,>>,##,..,## ##,##,##,##,##,..,##  // the small right loop sets a clone of fib(n+1) to fib(n+1)+f(n).
##,MM,##,..,##,..,##,..,##,##,..,..,..,##,..,##  // (this technique is similar to brainfuck [->+&#x3C;])
##,..,**,FL,..,02,##,%R,..,##,..,##,PP,##,..,##  // the small loop at the bottom does nothing, but make sure
##,##,##,NL,##,##,##,%D,&#x3C;>,01,FR,..,..,##,..,##  // that the original fib(n+1) is synchronized with the other cars.
      ##,>>,##,##,##,..,##,##,03,##,##,##,..,##  // then fib(n+1) goes to left column and fib(n+1)+fib(n) to right column
      ##,(),##,..,..,FM,..,..,%R,..,..,..,..,##
      ##,##,##,..,##,..,##,##,##,##,##,##,##,##
            ##,..,..,..,##
            ##,##,##,##,##
PP-> +=1
MM-> -=1
FR-> IF ** THEN %U ELSE %D
FL-> IF ==0 THEN %D ELSE %L
FM-> IF ** THEN %L ELSE %R
LD-> IF ** THEN %L ELSE %D
NL-> ="\n"
</code></pre>
<p>In this language, "cars" are spawned from the starting position <code>^^</code>, of which there can be only one per "map". Commas <code>,</code> are used to separate "cells" of the program and every cell is a two-character sequence. Cars cannot move through walls <code>##</code>, but instead follow the path <code>..</code> and have actions performed on them by functions, which are composed of two capital letters and are defined within the source code but outside of the maze, as seen above (<code>PP</code>, <code>MM</code>, etc.).</p>
<p><a href="https://github.com/olls">Oliver Faircliff</a> has even designed this nice, animated <a href="https://github.com/olls/maze-interpreter-v3">Maze interpreter in C++</a> which looks more like a low-budget smartphone game than a programming language.</p>
<p>There are a huge variety of two-dimensional (and <a href="https://esolangs.org/wiki/Category:Multi-dimensional_languages">higher-dimensional</a>) programming languages out there and many are quite a bit more complex than arrows directing the flow of the program. For example, the (as-yet-unimplemented) language <strong>Infinite Dimensional Tengwar Meltdown</strong> (IDTM) is an esoteric language written in the <a href="https://en.wikipedia.org/wiki/Tengwar">Tengwar</a> script from Lord of the Rings. It's an infinite-dimensional, pointer-based language where data exists on an array of infinite size and code decays via entropy over time (see also: <a href="https://esolangs.org/wiki/Entropy">Entropy</a>). So loops, which are run multiple times, will <em>degrade</em> and change their meaning over the course of the program.</p>
<p>Just when you thought esoteric languages couldn't get weirder.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="aesthetics"></a></p>
<h2>#18. languages which emphasise source code aesthetics</h2>
<p>When you think of the <em>aesthetics</em> of source code, you probably think about whitespace. The visual structure of a program is largely defined by blocks of code, blank lines, indentation, and more. You might not think about how the <em>characters</em> of the source code can affect its aesthetic properties. For instance, characters with lots of curves can give a "wavy", "bubbly", or "smooth" appearance:</p>
<pre><code>s@Ss@S$3CO0oc896$3Cs@S$3CO0oc896O0os@S$3CO0oc896c896
</code></pre>
<p>...while characters with lots of straight lines can communicate "jaggedness", "sharpness", or "clutter":</p>
<pre><code>/\|EL/H>+-_=IT\MN|F#^&#x3C;ZK/k\vx|/>+V|Xzw/WF#^&#x3C;ZK/k\vx|/>+-_=\
</code></pre>
<p>Some language designers <em>have indeed</em> thought about the aesthetic properties of certain characters and have used them to achieve a particular goal with their languages. For instance, the creator of <a href="http://www.blue.sky.or.jp/grass/">Grass</a> wanted to make a language where the source code looks like an unkempt lawn. All Grass source code is written using only the characters <code>w</code>, <code>W</code>, and <code>v</code>:</p>
<pre><code>　　　　_, ._
　　（　・ω・）　んも〜
　　○=｛=｝〇,
　 　|:::::::::＼, ', ´
､､､､し ､､､((（.＠）ｗｖｗｗＷＷｗｖｗｗＷｗｗｖｗｗｗｗＷＷＷｗｗＷｗ
ｗＷＷＷＷＷＷｗｗｗｗＷｗｗｖｗＷＷｗＷｗｗｖｗＷＷＷ

作ってみたｗｗｗｗｗ
とりあえず公開ｗｗｗｗｗｗｗっうぇ
</code></pre>
<p>Other language designers require their source code to resemble some kind of <a href="https://en.wikipedia.org/wiki/ASCII_art">ASCII art</a>, like <a href="https://esolangs.org/wiki/DNA-Sharp">DNA#</a> (a play on C#), which has source code that looks like DNA double-helices:</p>
<pre><code>    AT
   T--A
  A----T
  T-----A
  T-----A
  G----C
   T--A
    GC
    CG
   C--G
  A----T
  A-----T
  T-----A
  A----T
   A--T
    GC
    AT
   C--G
  T----A
  C-----G
  T-----A
  G----C
   C--G
    CG
...
</code></pre>
<p>If you're interested in these kinds of languages, there are many descriptions for as-yet-unimplemented programming languages like these over at <a href="https://esolangs.org/wiki/Main_Page">esolangs.org</a>, including:</p>
<p>...<a href="https://esolangs.org/wiki/Cactusi">Cactusi</a>, whose source code should look like cactuses in a desert (or the <a href="https://elgoog.im/t-rex/">Google Chrome dinosaur game</a>)</p>
<pre><code>     ||    ||  
   ==||   =||=
_____||____||____
</code></pre>
<p>...<a href="https://esolangs.org/wiki/Tree">Tree</a>, which is meant to look like, well, a tree (or a shrub of some kind):</p>
<pre><code>      ^
    ^^|^^
   ^^\|/^^
   H^ |/^^^
     \| e
      |/
   ol~|
     \|
  , 32|
   \/ |
    \ |  W
 l   \| /
 \  d |/  o
  \/ !|r /  
   \/ |\/
    \ |/
     \|
</code></pre>
<p>...or <a href="https://esolangs.org/wiki/Rotary">Rotary</a>, a BF derivative where source code must be written in circles:</p>
<pre><code>     !!!,.v
  !!!      !!!
 !            !
!              !
!              !
!              !
 !            !
  !!!      !!!
     !!!!!!

     !!!,.^
  !!!      !!!
 !            !
!              !
!              !
!              !
 !            !
  !!!      !!!
     !!!!!!
</code></pre>
<p>"Source code as art" is certainly a concept that is alive and well, at least among the esolang community.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="imitation"></a></p>
<h2>#19. languages built so that the source code looks like ___</h2>
<p>In a slightly different category from those languages in <a href="#aesthetics">#18</a> are the following languages, which are written using reduced character sets, or add lots of extra "decoration" in an attempt to make the language look like...</p>
<h3>a recipe</h3>
<p>The <a href="https://esolangs.org/wiki/Chef">Chef</a> programming language (not to be confused with the <a href="https://en.wikipedia.org/wiki/Chef_(software)">Chef configuration management tool</a>), is a language designed so that its source code looks like a recipe. Here's a "Hello, World!" program in Chef:</p>
<pre><code>Hello World Souffle.

This recipe prints the immortal words "Hello world!", in a basically brute force way. It also makes a lot of food for one person.

Ingredients.
72 g haricot beans
101 eggs
108 g lard
111 cups oil
32 zucchinis
119 ml water
114 g red salmon
100 g dijon mustard
33 potatoes

Method.
Put potatoes into the mixing bowl. Put dijon mustard into the mixing bowl. Put lard into the mixing bowl. Put red salmon into the mixing bowl. Put oil into the mixing bowl. Put water into the mixing bowl. Put zucchinis into the mixing bowl. Put oil into the mixing bowl. Put lard into the mixing bowl. Put lard into the mixing bowl. Put eggs into the mixing bowl. Put haricot beans into the mixing bowl. Liquefy contents of the mixing bowl. Pour contents of the mixing bowl into the baking dish.

Serves 1.
</code></pre>
<p>One of Chef's design principles is that "[p]rogram recipes should not only generate valid output, but be easy to prepare and delicious." Whether or not the above souflée recipe is "delicious" is, I suppose, open to interpretation, but there is a <a href="http://www.mike-worth.com/2013/03/31/baking-a-hello-world-cake/">different "Hello, World!" recipe</a> that makes a surprisingly good chocolate cake.</p>
<h3>Braille</h3>
<p><a href="https://en.wikipedia.org/wiki/Louis_Braille">Louis Braille</a> is the inventor of the tactile writing system for the visually impaired now known commonly as <a href="https://en.wikipedia.org/wiki/Braille">braille</a> (all-lowercase), but he also lends his surname to the programming language <a href="https://esolangs.org/wiki/Braille">Braille</a> (capitalised).</p>
<p>Braille (the programming language) is written using only the UNICODE braille codes (U+2800 to U+28FF). As there are 256 codes (written on a 2x8 grid), the creator of Braille (Brian McPherson) decided to arrange them in a 16x16 grid, where there are 16 actions that can be performed along with a single hexadecimal digit passed to that action.</p>
<p>Here's a Braille program that prints "Hello, World!" in ASCII characters:</p>
<pre><code> ⠆⠄⡒⡆⡘⠀⢐⠊⠦⢦⠗⢾⠿⠂⢢⢾⢦⢦⠮⢄
</code></pre>
<p>And a "Hello, World!" that prints its output in braille:</p>
<pre><code> ⠆⡆⢤⡔⠈⠖⠙⠇⠗⠕⠺⠀⠂⠕⠇⠇⠑⠓
</code></pre>
<h3>a play</h3>
<p>The (in)famous <a href="https://esolangs.org/wiki/Shakespeare">Shakespeare</a> language adds lots of extra decoration to the source code so that it resembles one of the plays of its namesake. The language's creators summarise it as follows:</p>
<blockquote>
<p><em>"The characters in the play are variables. If you want to assign a character, let's say Hamlet, a negative value, you put him and another character on the stage and let that character insult Hamlet.</em></p>
<p><em>Input and output [are] done be having someone tell a character to listen [to] their heart [or] speak their mind. The language contains conditionals, where characters ask each other questions, and jumps, where they decide to go to a specific act or scene. Characters are also stacks that can be pushed and popped."</em></p>
</blockquote>
<p>There's a <a href="http://shakespearelang.sourceforge.net/report/shakespeare/#SECTION00091000000000000000">"Hello, World!"</a> written in Shakespeare that's just a bit too long to reproduce here, but here's a program which takes any input, reverses it, and prints the reversed string:</p>
<pre><code>Outputting Input Reversedly.

Othello, a stacky man.
Lady Macbeth, who pushes him around till he pops.


                    Act I: The one and only.

                    Scene I: In the beginning, there was nothing.

[Enter Othello and Lady Macbeth]

Othello:
 You are nothing!

                    Scene II: Pushing to the very end.

Lady Macbeth:
 Open your mind! Remember yourself.

Othello:
 You are as hard as the sum of yourself and a stone wall. Am I as
 horrid as a flirt-gill?

Lady Macbeth:
 If not, let us return to scene II. Recall your imminent death!

Othello:
 You are as small as the difference between yourself and a hair!

                    Scene III: Once you pop, you can't stop!

Lady Macbeth:
 Recall your unhappy childhood. Speak your mind!

Othello:
 You are as vile as the sum of yourself and a toad! Are you better
 than nothing?

Lady Macbeth:
 If so, let us return to scene III.

                    Scene IV: The end.

[Exeunt]
</code></pre>
<h3>rock lyrics</h3>
<p>The <a href="https://esolangs.org/wiki/Rockstar">Rockstar</a> language is designed so that its source code looks like lyrics to a cheesy 80s rock ballad. It was created by Dylan Beattie in 2018, inspired by <a href="https://twitter.com/paulstovell/status/1013960369465782273?lang=en">a tweet</a> which suggested that someone should develop a language called Rockstar to confuse recruiters, who are always looking for "rockstar developers" for their clients.</p>
<p>Here's FizzBuzz in Rockstar:</p>
<pre><code> Midnight takes your heart and your soul
 While your heart is as high as your soul
 Put your heart without your soul into your heart
 
 Give back your heart
 
 
 Desire is a lovestruck ladykiller
 My world is nothing 
 Fire is ice
 Hate is water
 Until my world is Desire,
 Build my world up
 If Midnight taking my world, Fire is nothing and Midnight taking my world, Hate is nothing
 Shout "FizzBuzz!"
 Take it to the top
 
 If Midnight taking my world, Fire is nothing
 Shout "Fizz!"
 Take it to the top
 
 If Midnight taking my world, Hate is nothing
 Say "Buzz!"
 Take it to the top
   
 Whisper my world
</code></pre>
<h3>fetish erotica</h3>
<p>Last but not least is <a href="https://esolangs.org/wiki/Fetlang">Fetlang</a>, a very NSFW language whose source code resembles <a href="https://github.com/fetlang/fetlang">fetish erotica</a>, and is "licensed under the BSDM (BSD, modified) license".</p>
<p>Here's a relatively tame Fetlang program that just echoes the arguments passed to it:</p>
<pre><code>Make Sean moan
Worship Carrie's feet

Bind Amy to Saint Andrew's Cross
    Have Amy hogtie Sean
    If Amy is Carrie's bitch
        Make Slave scream Sean's name
        Make Sean moan
</code></pre>
<p>It only gets more risqué from there.</p>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<p><a name="qsharp"></a></p>
<h2>#20. Q#</h2>
<p>"The future is quantum", asserted IBM in <a href="https://www.ibm.com/blogs/research/2017/11/the-future-is-quantum/">a 2017 blog post</a>, which conveniently touted their own quantum computer, the IBM Q. The theoretical foundations of quantum computing were laid by Paul Benioff, Richard Feynman, and many others <a href="https://en.wikipedia.org/wiki/Quantum_computing">in the early 1980s</a>, but it's only recently that engineering has caught up to theory and the construction of quantum computers like the IBM Q has become possible.</p>
<p>Quantum computing offers immense advantages over traditional (classical) computing in particular domains like cryptography, physical simulations, and highly-parallelisable problems like solving systems of equations. Recently, Google proclaimed <a href="https://www.nature.com/articles/s41586-019-1666-5"><em>quantum supremacy</em></a> with an algorithm that ran on their 54-qubit Sycamore quantum processor in just 200 seconds. An equivalent algorithm would require 10,000 years of processing time on a state-of-the-art classical supercomputer, rendering it practically impossible.</p>
<p>Programming a quantum computer is entirely different from programming a classical computer, because quantum effects like entanglement, coherence, and uncertainty come into play. Even at the most fundamental level, quantum programming differs from classical programming. The traditional logical AND, OR, and NOT gates are replaced by <a href="https://en.wikipedia.org/wiki/Hadamard_gate">Hadamard gates</a>, <a href="https://en.wikipedia.org/wiki/Toffoli_gate">Toffoli gates</a>, and <a href="https://en.wikipedia.org/wiki/Pauli_matrices">Pauli X, Y, Z gates</a>. It is <em>not</em> a matter of simply learning a new programming language to learn quantum computing, but rather like learning an entirely new, extremely difficult skill (with a lot of mathematics and physics behind it).</p>
<p>Still, Microsoft has attempted to make the transition from classical programming to quantum programming as smooth as possible with their <a href="https://en.wikipedia.org/wiki/Q_Sharp">Q# programming language</a>, first released to the public in late 2017. Q# joins Microsoft's "sharp" family of programming languages, preceded by C# and F#. There are extensions for Q# for Microsoft's Visual Studio and <a href="https://marketplace.visualstudio.com/items?itemName=quantum.quantum-devkit-vscode">VS Code</a> IDEs, which are packaged with quantum simulators (since most people don't yet have access to actual quantum computers).</p>
<p>Q# code looks quite similar to C# code, and Microsoft have provided lots of helpful documentation and <a href="https://docs.microsoft.com/en-us/quantum/quickstart?view=qsharp-preview&#x26;tabs=tabid-python">examples</a> for you to get started. Because Q# is designed to run on actual quantum computers, it is usually run from within another language (like Python or C#), and the quantum simulator from that language interacts with Q#.</p>
<p>For example, here's a bit of Q# code, that -- when called within C# host code -- will measure the value of one of a pair of <a href="https://en.wikipedia.org/wiki/Quantum_entanglement">entangled</a> qubits, followed by the second one. The same value will <em>always</em> be returned due to the entangled state:</p>
<pre><code class="hljs language-c#">operation TestBellState(count : Int, initial : Result) : (Int, Int, Int) {
  mutable numOnes = 0;
  mutable agree = 0;

  using ((q0, q1) = (Qubit(), Qubit())) {
    for (test in 1..count) {
      Set(initial, q0);
      Set(Zero, q1);

      H(q0);
      CNOT(q0, q1);
      let res = M(q0);

      if (M(q1) == res) {
        set agree += 1;
      }

      // Count the number of ones we saw:
      if (res == One) {
        set numOnes += 1;
      }
    }
    
    Set(Zero, q0);
    Set(Zero, q1);
  }

  // Return number of times we saw a |0> and number of times we saw a |1>
  return (count-numOnes, numOnes, agree);
}
</code></pre>
<p><a href="#toc">[ back to Table of Contents ]</a></p>
<hr>
<p>Programming languages, like real-world languages, come in a wide variety of shapes and forms. Not every language needs to be declarative, or functional, or object-oriented. A language doesn't even need to have the ability to define named variables or functions in order to be able to compute anything you throw at it. There are a huge range of possibilities, as the above list attests to.</p>
<p>If you're as fascinated with programming languages as I am, I recommend you pay a visit to <a href="https://esolangs.org/">esolangs.org</a>, where you can learn more about these and many other esoteric languages. If you're interested in creating your own programming language, <strong>watch this space</strong>. I hope to put out a guide within the next few months on developing your own language and compiler from scratch!</p>
<hr>
<p>If you liked what you read above, you should follow me on <a href="https://dev.to/awwsmm">Dev.To</a> or <a href="https://twitter.com/_awwsmm">Twitter</a> to get more of that sweet, sweet content. If you <em>really</em> liked it, maybe you could support me by donating just a few of your country's currency units to me at <a href="https://ko-fi.com/awwsmm">Ko-Fi</a>.</p>
<p>Whatever you do, thanks for reading!</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[101 Bash Commands and Tips for Beginners to Experts]]></title>
            <link>https://awwsmm.com/blog/101-bash-commands-and-tips-for-beginners-to-experts</link>
            <guid isPermaLink="false">101-bash-commands-and-tips-for-beginners-to-experts</guid>
            <pubDate>Sun, 13 Jan 2019 00:00:00 GMT</pubDate>
            <description><![CDATA[A tour of the shell, from the simple and easy to the fun-but-mostly-useless.]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><blockquote>
<p>Originally posted on <a href="https://dev.to/awwsmm/101-bash-commands-and-tips-for-beginners-to-experts-30je">Dev.To</a></p>
</blockquote>
<blockquote>
<p><strong>Update 25 Sep 2019:</strong> This article is now available in Japanese, thanks to the hard work of <a href="https://twitter.com/rana_kualu">ラナ・クアール</a>. Please check out their work by following the link below. If you're aware of translations of this article to other languages, please let me know and I'll post them here.</p>
</blockquote>
<p><a href="https://qiita.com/rana_kualu/items/7b62898d373901466f5c">🇯🇵 日本語で読む</a></p>
<blockquote>
<p><strong>Update 8 July 2019:</strong> I recently found <a href="https://bookmarks.ecyseo.net/?EAWvDw">this very similar article</a> posted to a French-language message board about two years ago. If you're interested in learning some shell commands -- and you <em>parler français</em>, it's a great supplement to my article, below.</p>
</blockquote>
<p>Until about a year ago, I worked almost exclusively within the macOS and Ubuntu operating systems. On both of those OSes, <code>bash</code> is my default shell. I've acquired a general understanding of how <code>bash</code> works over the past six or seven years and would like to give an overview of some of the more common / useful commands for those just getting started. If you think you know everything there is to know about <code>bash</code>, take a look below anyway -- I've included some tips and reminders of flags you may have forgotten about, which could make your work a bit easier.</p>
<p>The commands below are laid out in a more-or-less narrative style, so if you're just getting started with <code>bash</code>, you can work your way through from the beginning to the end. Things generally get less common and more difficult toward the end.</p>
<p><a name="toc"></a></p>
<h2>Table of Contents</h2>
<ul>
<li><a href="#the-basics">The Basics</a>
<ul>
<li><a href="#first-commands">First Commands, Navigating the Filesystem</a>
<ul>
<li><a href="#pwd-ls-cd"><code>pwd / ls / cd</code></a></li>
<li><a href="#semicolon-andand-and"><code>; / &#x26;&#x26; / &#x26;</code></a></li>
</ul>
</li>
<li><a href="#getting-help">Getting Help</a>
<ul>
<li><a href="#minus-h"><code>-h</code></a></li>
<li><a href="#man"><code>man</code></a></li>
</ul>
</li>
<li><a href="#viewing-and-editing-files">Viewing and Editing Files</a>
<ul>
<li><a href="#head-tail-cat-less"><code>head / tail / cat / less</code></a></li>
<li><a href="#nano-nedit"><code>nano / nedit</code></a></li>
</ul>
</li>
<li><a href="#creating-and-deleting-files">Creating and Deleting Files and Directories</a>
<ul>
<li><a href="#touch"><code>touch</code></a></li>
<li><a href="#mkdir-rm-rmdir"><code>mkdir / rm / rmdir</code></a></li>
</ul>
</li>
<li><a href="#moving-and-copying-files">Moving and Copying Files, Making Links, Command History</a>
<ul>
<li><a href="#mv-cp-ln"><code>mv / cp / ln</code></a></li>
<li><a href="#command-history">Command History</a></li>
</ul>
</li>
<li><a href="#directory-trees-disk-usage-processes">Directory Trees, Disk Usage, and Processes</a>
<ul>
<li><a href="#mkdir--p-tree"><code>mkdir –p / tree</code></a></li>
<li><a href="#df-du-ps"><code>df / du / ps</code></a></li>
</ul>
</li>
<li><a href="#basic-misc">Miscellaneous</a>
<ul>
<li><a href="#passwd-logout-exit"><code>passwd / logout / exit</code></a></li>
<li><a href="#clear-glob"><code>clear / *</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#intermediate">Intermediate</a>
<ul>
<li><a href="#disk-memory-processor">Disk, Memory, and Processor Usage</a>
<ul>
<li><a href="#ncdu"><code>ncdu</code></a></li>
<li><a href="#top-htop"><code>top / htop</code></a></li>
</ul>
</li>
<li><a href="#REPLs-software-versions">REPLs and Software Versions</a>
<ul>
<li><a href="#REPLs">REPLs</a></li>
<li><a href="#version"><code>-version / --version / -v</code></a></li>
</ul>
</li>
<li><a href="#env-vars-aliases">Environment Variables and Aliases</a>
<ul>
<li><a href="#env-vars">Environment Variables</a></li>
<li><a href="#aliases">Aliases</a></li>
</ul>
</li>
<li><a href="#basic-bash-scripting">Basic <code>bash</code> Scripting</a>
<ul>
<li><a href="#bash-scripts"><code>bash</code> Scripts</a></li>
<li><a href="#custom-prompt-ls">Custom Prompt and <code>ls</code></a></li>
</ul>
</li>
<li><a href="#config-files">Config Files</a>
<ul>
<li><a href="#config-bashrc">Config Files / <code>.bashrc</code></a></li>
<li><a href="#types-of-shells">Types of Shells</a></li>
</ul>
</li>
<li><a href="#finding-things">Finding Things</a>
<ul>
<li><a href="#whereis-which-whatis"><code>whereis / which / whatis</code></a></li>
<li><a href="#locate-find"><code>locate / find</code></a></li>
</ul>
</li>
<li><a href="#downloading-things">Downloading Things</a>
<ul>
<li><a href="#ping-wget-curl"><code>ping / wget / curl</code></a></li>
<li><a href="#apt-gunzip-tar-gzip"><code>apt / gunzip / tar / gzip</code></a></li>
</ul>
</li>
<li><a href="#redirecting-io">Redirecting Input and Output</a>
<ul>
<li><a href="#pipe-gt-lt-echo-printf"><code>| / > / &#x3C; / echo / printf</code></a></li>
<li><a href="#std-tee"><code>0 / 1 / 2 / tee</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#advanced">Advanced</a>
<ul>
<li><a href="#superuser">Superuser</a>
<ul>
<li><a href="#sudo-su"><code>sudo / su</code></a></li>
<li><a href="#click-click"><code>!!</code></a></li>
</ul>
</li>
<li><a href="#file-permissions">File Permissions</a>
<ul>
<li><a href="#file-permissions-sub">File Permissions</a></li>
<li><a href="#chmod-chown"><code>chmod / chown</code></a></li>
</ul>
</li>
<li><a href="#users-groups">User and Group Management</a>
<ul>
<li><a href="#users">Users</a></li>
<li><a href="#groups">Groups</a></li>
</ul>
</li>
<li><a href="#text-processing">Text Processing</a>
<ul>
<li><a href="#uniq-sort-diff-cmp"><code>uniq / sort / diff / cmp</code></a></li>
<li><a href="#cut-sed"><code>cut / sed</code></a></li>
</ul>
</li>
<li><a href="#pattern-matching">Pattern Matching</a>
<ul>
<li><a href="#grep"><code>grep</code></a></li>
<li><a href="#awk"><code>awk</code></a></li>
</ul>
</li>
<li><a href="#ssh">Copying Files Over <code>ssh</code></a>
<ul>
<li><a href="#ssh-scp"><code>ssh / scp</code></a></li>
<li><a href="#rsync"><code>rsync</code></a></li>
</ul>
</li>
<li><a href="#long-running-processes">Long-Running Processes</a>
<ul>
<li><a href="#yes-nohup-ps-kill"><code>yes / nohup / ps / kill</code></a></li>
<li><a href="#cron"><code>cron / crontab / >></code></a></li>
</ul>
</li>
<li><a href="#advanced-misc">Miscellaneous</a>
<ul>
<li><a href="#pushd-popd"><code>pushd / popd</code></a></li>
<li><a href="#xdg-open"><code>xdg-open</code></a></li>
<li><a href="#xargs"><code>xargs</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#bonus">Bonus: Fun-But-Mostly-Useless Things</a>
<ul>
<li><a href="#w-write-wall-lynx"><code>w / write / wall / lynx</code></a></li>
<li><a href="#nautilus-date-cal-bc"><code>nautilus / date / cal / bc</code></a></li>
</ul>
</li>
</ul>
<br>
<hr>
<h1><a name="the-basics">The Basics</a></h1>
<h2><a name="first-commands">First Commands, Navigating the Filesystem</a></h2>
<p>Modern filesystems have directory (folder) trees, where a directory is either a <em>root directory</em> (with no parent directory) or is a <em>subdirectory</em> (contained within a single other directory, which we call its "parent"). Traversing backwards through the file tree (from child directory to parent directory) will always get you to the root directory. Some filesystems have multiple root directories (like Windows' drives: <code>C:\</code>, <code>A:\</code>, etc.), but Unix and Unix-like systems only have a single root directory called <code>\</code>.</p>
<p><a name="pwd-ls-cd"></a></p>
<h3><code>pwd / ls / cd</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>When working within a filesystem, the user is always working <em>within</em> some directory, which we call the current directory or the <em>working directory</em>. Print the user's working directory with <code>pwd</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ pwd
/home/andrew
</code></pre>
<p>List the contents of this directory (files and/or child directories, etc.) with <code>ls</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ls
Git  TEST  jdoc  test  test.file
</code></pre>
<blockquote>
<p><strong>Bonus:</strong></p>
<p>Show hidden ("dot") files with <code>ls -a</code></p>
<p>Show file details with <code>ls -l</code></p>
<p>Combine multiple flags like <code>ls -l -a</code></p>
<p>You can sometimes chain flags like <code>ls -la</code> instead of <code>ls -l -a</code></p>
</blockquote>
<p>Change to a different directory with <code>cd</code> (change directory):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ cd TEST/

[ andrew@pc01 TEST ]$ pwd
/home/andrew/TEST

[ andrew@pc01 TEST ]$ cd A

[ andrew@pc01 A ]$ pwd
/home/andrew/TEST/A
</code></pre>
<p><code>cd ..</code> is shorthand for "<code>cd</code> to the parent directory”:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 A ]$ cd ..

[ andrew@pc01 TEST ]$ pwd
/home/andrew/TEST
</code></pre>
<p><code>cd ~</code> or just <code>cd</code> is shorthand for "<code>cd</code> to my home directory" (usually <code>/home/username</code> or something similar):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 TEST ]$ cd

[ andrew@pc01 ~ ]$ pwd
/home/andrew
</code></pre>
<blockquote>
<p><strong>Bonus:</strong></p>
<p><code>cd ~user</code> means "<code>cd</code> to <code>user</code>'s home directory</p>
<p>You can jump multiple directory levels with <code>cd ../..</code>, etc.</p>
<p>Go back to the most recent directory with <code>cd -</code></p>
<p><code>.</code> is shorthand for "this directory", so <code>cd .</code> won't do much of anything</p>
</blockquote>
<p><a name="semicolon-andand-and"></a></p>
<h3><code>; / &#x26;&#x26; / &#x26;</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>The things we type into the command line are called <em>commands</em>, and they always execute some machine code stored somewhere on your computer. Sometimes this machine code is a built-in Linux command, sometimes it's an app, sometimes it's some code that you wrote yourself. Occasionally, we'll want to run one command right after another. To do that, we can use the <code>;</code> (semicolon):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ls; pwd
Git  TEST  jdoc  test  test.file
/home/andrew
</code></pre>
<p>Above, the semicolon means that I first (<code>ls</code>) list the contents of the working directory, and then I (<code>pwd</code>) print its location. Another useful tool for chaining commands is <code>&#x26;&#x26;</code>. With <code>&#x26;&#x26;</code>, the command to the right will not run if the command to the left fails. <code>;</code> and <code>&#x26;&#x26;</code> can both be used multiple times on the same line:</p>
<pre><code class="hljs language-bash"># whoops! I made a typo here!
[ andrew@pc01 ~ ]$ cd /Giit/Parser &#x26;&#x26; pwd &#x26;&#x26; ls &#x26;&#x26; cd
-bash: cd: /Giit/Parser: No such file or directory

# the first command passes now, so the following commands are run
[ andrew@pc01 ~ ]$ cd Git/Parser/ &#x26;&#x26; pwd &#x26;&#x26; ls &#x26;&#x26; cd
/home/andrew/Git/Parser
README.md  doc.sh  pom.xml  resource  run.sh  shell.sh  source  src  target
</code></pre>
<p>...but with <code>;</code>, the second command will run even if the first one fails:</p>
<pre><code class="hljs language-bash"># pwd and ls still run, even though the cd command failed
[ andrew@pc01 ~ ]$ cd /Giit/Parser ; pwd ; ls
-bash: cd: /Giit/Parser: No such file or directory
/home/andrew
Git  TEST  jdoc  test  test.file
</code></pre>
<p><code>&#x26;</code> looks similar to <code>&#x26;&#x26;</code> but actually fulfils a completely different function. Normally, when you execute a long-running command, the command line will wait for that command to finish before it allows you to enter another one. Putting <code>&#x26;</code> after a command prevents this from happening, and lets you execute a new command while an older one is still going:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ cd Git/Parser &#x26;&#x26; mvn package &#x26; cd
[1] 9263
</code></pre>
<blockquote>
<p><strong>Bonus:</strong> When we use <code>&#x26;</code> after a command to "hide" it, we say that the job (or the "process"; these terms are more or less interchangeable) is "backgrounded". To see what background jobs are currently running, use the <code>jobs</code> command:</p>
</blockquote>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ jobs
[1]+ Running cd Git/Parser/ &#x26;&#x26; mvn package &#x26;
</code></pre>
<p><a name="getting-help"></a></p>
<h2>Getting Help</h2>
<p><a name="minus-h"></a></p>
<h3><code>-h</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>Type <code>-h</code> or <code>--help</code> after almost any command to bring up a help menu for that command:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ du --help
Usage: du [OPTION]... [FILE]...
  or:  du [OPTION]... --files0-from=F
Summarize disk usage of the set of FILEs, recursively for directories.

Mandatory arguments to long options are mandatory for short options too.
  -0, --null            end each output line with NUL, not newline
  -a, --all             write counts for all files, not just directories
      --apparent-size   print apparent sizes, rather than disk usage; although
                          the apparent size is usually smaller, it may be
                          larger due to holes in ('sparse') files, internal
                          fragmentation, indirect blocks, and the like
  -B, --block-size=SIZE  scale sizes by SIZE before printing them; e.g.,
                           '-BM' prints sizes in units of 1,048,576 bytes;
                           see SIZE format below
...
</code></pre>
<p><a name="man"></a></p>
<h3><code>man</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>Type <code>man</code> before almost any command to bring up a manual for that command (quit <code>man</code> with <code>q</code>):</p>
<pre><code class="hljs language-bash">LS(1)                            User Commands                           LS(1)

NAME
       ls - list directory contents

SYNOPSIS
       ls [OPTION]... [FILE]...

DESCRIPTION
       List  information  about  the FILEs (the current directory by default).
       Sort entries alphabetically if none of -cftuvSUX nor --sort  is  speci-
       fied.

       Mandatory  arguments  to  long  options are mandatory for short options
       too.
...
</code></pre>
<p><a name="viewing-and-editing-files"></a></p>
<h2>Viewing and Editing Files</h2>
<p><a name="head-tail-cat-less"></a></p>
<h3><code>head / tail / cat / less</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>head</code> outputs the first few lines of a file. The <code>-n</code> flag specifies the number of lines to show (the default is 10):</p>
<pre><code class="hljs language-bash"># prints the first three lines
[ andrew@pc01 ~ ]$ head -n 3 c
this
file
has
</code></pre>
<p><code>tail</code> outputs the last few lines of a file. You can get the last <code>n</code> lines (like above), or you can get the end of the file beginning from the <code>N</code>-th line with <code>tail -n +N</code>:</p>
<pre><code class="hljs language-bash"># prints the end of the file, beginning with the 4th line
[ andrew@pc01 ~ ]$ tail -n +4 c
exactly
six
lines
</code></pre>
<p><code>cat</code> concatenates a list of files and sends them to the standard output stream (usually the terminal). <code>cat</code> can be used with just a single file, or multiple files, and is often used to quickly view them. (<strong>Be warned</strong>: if you use <code>cat</code> in this way, you may be accused of a <a href="http://bit.ly/2SPHE4V"><em>Useless Use of Cat</em> (UUOC)</a>, but it's not that big of a deal, so don't worry too much about it.)</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ cat a
file a

[ andrew@pc01 ~ ]$ cat a b
file a
file b
</code></pre>
<p><code>less</code> is another tool for quickly viewing a file -- it opens up a <code>vim</code>-like read-only window. (Yes, there is a command called <code>more</code>, but <code>less</code> -- unintuitively -- offers a superset of the functionality of <code>more</code> and is recommended over it.) Learn more (or less?) about <a href="http://man7.org/linux/man-pages/man1/less.1.html">less</a> and <a href="http://man7.org/linux/man-pages/man1/more.1.html">more</a> at their <code>man</code> pages.</p>
<p><a name="nano-nedit"></a></p>
<h3><code>nano / nedit</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>nano</code> is a minimalistic command-line text editor. It's a great editor for beginners or people who don't want to learn a million shortcuts. It was more than sufficient for me for the first few years of my coding career (I'm only now starting to look into more powerful editors, mainly because defining your own syntax highlighting in <code>nano</code> can be a bit of a pain.)</p>
<p><code>nedit</code> is a small graphical editor, it opens up an X Window and allows point-and-click editing, drag-and-drop, syntax highlighting and more. I use <code>nedit</code> sometimes when I want to make small changes to a script and re-run it over and over.</p>
<p>Other common CLI (command-line interface) / GUI (graphical user interface) editors include <code>emacs</code>, <code>vi</code>, <code>vim</code>, <code>gedit</code>, Notepad++, Atom, and lots more. Some cool ones that I've played around with (and can endorse) include Micro, Light Table, and VS Code.</p>
<p>All modern editors offer basic conveniences like search and replace, syntax highlighting, and so on. <code>vi(m)</code> and <code>emacs</code> have more features than <code>nano</code> and <code>nedit</code>, but they have a much steeper learning curve. Try a few different editors out and find one that works for you!</p>
<p><a name="creating-and-deleting-files"></a></p>
<h2>Creating and Deleting Files and Directories</h2>
<p><a name="touch"></a></p>
<h3><code>touch</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>touch</code> was created to modify file timestamps, but it can also be used to quickly create an empty file. You can create a new file by opening it with a text editor, like <code>nano</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ ls

[ andrew@pc01 ex ]$ nano a
</code></pre>
<p><em>...editing file...</em></p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ ls
a
</code></pre>
<p>...or by simply using <code>touch</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ touch b &#x26;&#x26; ls
a  b
</code></pre>
<blockquote>
<p><strong>Bonus</strong>:</p>
<p>Background a process with ^z (Ctrl+z)</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ nano a
</code></pre>
<p><em>...editing file, then hit ^z...</em></p>
<pre><code class="hljs language-bash">Use fg to return to nano

[1]+ Stopped nano a
[ andrew@pc01 ex ]$ fg
</code></pre>
<p><em>...editing file again...</em></p>
</blockquote>
<hr>
<blockquote>
<p><strong>Double Bonus:</strong></p>
<p>Kill the current (foreground) process by pressing ^c (Ctrl+c) while it’s running</p>
<p>Kill a background process with <code>kill %N</code> where <code>N</code> is the job index shown by the <code>jobs</code> command</p>
</blockquote>
<p><a name="mkdir-rm-rmdir"></a></p>
<h3><code>mkdir / rm / rmdir</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>mkdir</code> is used to create new, empty directories:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ ls &#x26;&#x26; mkdir c &#x26;&#x26; ls
a  b
a  b  c
</code></pre>
<p>You can remove any file with <code>rm</code> -- but be careful, this is non-recoverable!</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ rm a &#x26;&#x26; ls
b  c
</code></pre>
<p>You can add an <em>"are you sure?"</em> prompt with the <code>-i</code> flag:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ rm -i b
rm: remove regular empty file 'b'? y
</code></pre>
<p>Remove an empty directory with <code>rmdir</code>. If you <code>ls -a</code> in an empty directory, you should only see a reference to the directory itself (<code>.</code>) and a reference to its parent directory (<code>..</code>):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ rmdir c &#x26;&#x26; ls -a
.  ..
</code></pre>
<p><code>rmdir</code> removes empty directories only:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ cd .. &#x26;&#x26; ls test/
*.txt  0.txt  1.txt  a  a.txt  b  c

[ andrew@pc01 ~ ]$ rmdir test/
rmdir: failed to remove 'test/': Directory not empty
</code></pre>
<p>...but you can remove a directory -- and all of its contents -- with <code>rm -rf</code> (<code>-r</code> = recursive, <code>-f</code> = force):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ rm –rf test
</code></pre>
<p><a name="moving-and-copying-files"></a></p>
<h2>Moving and Copying Files, Making Links, Command History</h2>
<p><a name="mv-cp-ln"></a></p>
<h3><code>mv / cp / ln</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>mv</code> moves / renames a file. You can <code>mv</code> a file to a new directory and keep the same file name or <code>mv</code> a file to a "new file" (rename it):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ ls &#x26;&#x26; mv a e &#x26;&#x26; ls
a  b  c  d
b  c  d  e
</code></pre>
<p><code>cp</code> copies a file:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ cp e e2 &#x26;&#x26; ls
b  c  d  e  e2
</code></pre>
<p><code>ln</code> creates a hard link to a file:</p>
<pre><code class="hljs language-bash"># first argument to ln is TARGET, second is NEW LINK
[ andrew@pc01 ex ]$ ln b f &#x26;&#x26; ls
b  c  d  e  e2  f
</code></pre>
<p><code>ln -s</code> creates a soft link to a file:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ ln -s b g &#x26;&#x26; ls
b  c  d  e  e2  f  g
</code></pre>
<p>Hard links reference the same actual bytes in memory which contain a file, while soft links refer to the original file name, which itself points to those bytes. <a href="http://bit.ly/2D0W8cN">You can read more about soft vs. hard links here.</a></p>
<p><a name="command-history"></a></p>
<h3>Command History</h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>bash</code> has two big features to help you complete and re-run commands, the first is <em>tab completion</em>. Simply type the first part of a command, hit the &#x3C;tab> key, and let the terminal guess what you're trying to do:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 dir ]$ ls &#x3C;ENTER>
anotherlongfilename  thisisalongfilename  anewfilename

[ andrew@pc01 dir ]$ ls t &#x3C;TAB>
</code></pre>
<p><em>...hit the TAB key after typing <code>ls t</code> and the command is completed...</em></p>
<pre><code class="hljs language-bash">[ andrew@pc01 dir ]$ ls thisisalongfilename &#x3C;ENTER>
thisisalongfilename
</code></pre>
<p>You may have to hit &#x3C;TAB> multiple times if there's an ambiguity:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 dir ]$ ls a &#x3C;TAB>

[ andrew@pc01 dir ]$ ls an &#x3C;TAB>
anewfilename  anotherlongfilename
</code></pre>
<p><code>bash</code> keeps a short history of the commands you've typed previously and lets you search through those commands by typing ^r (Ctrl+r):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 dir ]
</code></pre>
<p><em>...hit ^r (Ctrl+r) to search the command history...</em></p>
<pre><code class="hljs language-bash">(reverse-i-search)`':
</code></pre>
<p><em>...type 'anew' and the last command containing this is found...</em></p>
<pre><code class="hljs language-bash">(reverse-i-search)`anew': touch anewfilename
</code></pre>
<p><a name="directory-trees-disk-usage-processes"></a></p>
<h2>Directory Trees, Disk Usage, and Processes</h2>
<p><a name="mkdir--p-tree"></a></p>
<h3><code>mkdir –p / tree</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>mkdir</code>, by default, only makes a single directory. This means that if, for instance, directory <code>d/e</code> doesn't exist, then <code>d/e/f</code> can't be made with <code>mkdir</code> by itself:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ ls &#x26;&#x26; mkdir d/e/f
a  b  c
mkdir: cannot create directory 'd/e/f': No such file or directory
</code></pre>
<p>But if we pass the <code>-p</code> flag to <code>mkdir</code>, it will make all directories in the path if they don't already exist:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ mkdir -p d/e/f &#x26;&#x26; ls
a  b  c  d
</code></pre>
<p><code>tree</code> can help you better visualise a directory's structure by printing a nicely-formatted directory tree. By default, it prints the entire tree structure (beginning with the specified directory), but you can restrict it to a certain number of levels with the <code>-L</code> flag:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ tree -L 2
.
|-- a
|-- b
|-- c
`-- d
    `--e

3 directories, 2 files
</code></pre>
<p>You can hide empty directories in <code>tree</code>'s output with <code>--prune</code>. Note that this also removes "recursively empty" directories, or directories which aren't empty <em>per se</em>, but which contain only other empty directories, or other recursively empty directories:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ tree --prune
.
|-- a
`-- b
</code></pre>
<p><a name="df-du-ps"></a></p>
<h3><code>df / du / ps</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>df</code> is used to show how much space is taken up by files for the disks or your system (hard drives, etc.).</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ df -h
Filesystem                   Size  Used Avail Use% Mounted on
udev                         126G     0  126G   0% /dev
tmpfs                         26G  2.0G   24G   8% /run
/dev/mapper/ubuntu--vg-root  1.6T  1.3T  252G  84% /
...
</code></pre>
<p>In the above command, <code>-h</code> doesn't mean "help", but "human-readable". Some commands use this convention to display file / disk sizes with <code>K</code> for kilobytes, <code>G</code> for gigabytes, and so on, instead of writing out a gigantic integer number of bytes.</p>
<p><code>du</code> shows file space usage for a particular directory and its subdirectories. If you want to know how much space is free on a given hard drive, use <code>df</code>; if you want to know how much space a directory is taking up, use <code>du</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ du
4       ./d/e/f
8       ./d/e
12      ./d
4       ./c
20      .
</code></pre>
<p><code>du</code> takes a <code>--max-depth=N</code> flag, which only shows directories <code>N</code> levels down (or fewer) from the specified directory:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ du -h --max-depth=1
12K     ./d
4.0K    ./c
20K     .
</code></pre>
<p><code>ps</code> shows all of the user's currently-running processes (aka. jobs):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ex ]$ ps
  PID TTY          TIME CMD
16642 pts/15   00:00:00 ps
25409 pts/15   00:00:00 bash
</code></pre>
<p><a name="basic-misc"></a></p>
<h2>Miscellaneous</h2>
<p><a name="passwd-logout-exit"></a></p>
<h3><code>passwd / logout / exit</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>Change your account password with <code>passwd</code>. It will ask for your current password for verification, then ask you to enter the new password twice, so you don't make any typos:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 dir ]$ passwd
Changing password for andrew.
(current) UNIX password:    &#x3C;type current password>
Enter new UNIX password:    &#x3C;type new password>
Retype new UNIX password:   &#x3C;type new password again>
passwd: password updated successfully
</code></pre>
<p><code>logout</code> exits a shell you’ve logged in to (where you have a user account):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 dir ]$ logout

──────────────────────────────────────────────────────────────────────────────
Session stopped
    - Press &#x3C;return> to exit tab
    - Press R to restart session
    - Press S to save terminal output to file
</code></pre>
<p><code>exit</code> exits any kind of shell:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ exit
logout

──────────────────────────────────────────────────────────────────────────────
Session stopped
    - Press &#x3C;return> to exit tab
    - Press R to restart session
    - Press S to save terminal output to file
</code></pre>
<p><a name="clear-glob"></a></p>
<h3><code>clear / *</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>Run <code>clear</code> to move the current terminal line to the top of the screen. This command just adds blank lines below the current prompt line. It's good for clearing your workspace.</p>
<p>Use the glob (<code>*</code>, aka. Kleene Star, aka. wildcard) when looking for files. Notice the difference between the following two commands:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ls Git/Parser/source/
PArrayUtils.java     PFile.java            PSQLFile.java      PWatchman.java
PDateTimeUtils.java  PFixedWidthFile.java  PStringUtils.java  PXSVFile.java
PDelimitedFile.java  PNode.java            PTextFile.java     Parser.java

[ andrew@pc01 ~ ]$ ls Git/Parser/source/PD*
Git/Parser/source/PDateTimeUtils.java  Git/Parser/source/PDelimitedFile.java
</code></pre>
<p>The glob can be used multiple times in a command and matches zero or more characers:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ls Git/Parser/source/P*D*m*
Git/Parser/source/PDateTimeUtils.java  Git/Parser/source/PDelimitedFile.java
</code></pre>
<h1><a name="intermediate">Intermediate</a></h1>
<h2><a name="disk-memory-processor">Disk, Memory, and Processor Usage</a></h2>
<p><a name="ncdu"></a></p>
<h3><code>ncdu</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>ncdu</code> (NCurses Disk Usage) provides a navigable overview of file space usage, like an improved <code>du</code>. It opens a read-only <code>vim</code>-like window (press <code>q</code> to quit):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ncdu

ncdu 1.11 ~ Use the arrow keys to navigate, press ? for help
--- /home/andrew -------------------------------------------------------------
  148.2 MiB [##########] /.m2
   91.5 MiB [######    ] /.sbt
   79.8 MiB [#####     ] /.cache
   64.9 MiB [####      ] /.ivy2
   40.6 MiB [##        ] /.sdkman
   30.2 MiB [##        ] /.local
   27.4 MiB [#         ] /.mozilla
   24.4 MiB [#         ] /.nanobackups
   10.2 MiB [          ]  .confout3.txt
    8.4 MiB [          ] /.config
    5.9 MiB [          ] /.nbi
    5.8 MiB [          ] /.oh-my-zsh
    4.3 MiB [          ] /Git
    3.7 MiB [          ] /.myshell
    1.7 MiB [          ] /jdoc
    1.5 MiB [          ]  .confout2.txt
    1.5 MiB [          ] /.netbeans
    1.1 MiB [          ] /.jenv
  564.0 KiB [          ] /.rstudio-desktop
 Total disk usage: 552.7 MiB  Apparent size: 523.6 MiB  Items: 14618
</code></pre>
<p><a name="top-htop"></a></p>
<h3><code>top / htop</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>top</code> displays all currently-running processes and their owners, memory usage, and more. <code>htop</code> is an improved, interactive <code>top</code>. (Note: you can pass the <code>-u username</code> flag to restrict the displayed processes to only those owner by <code>username</code>.)</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ htop

  1  [       0.0%]   9  [       0.0%]   17 [       0.0%]   25 [       0.0%]
  2  [       0.0%]   10 [       0.0%]   18 [       0.0%]   26 [       0.0%]
  3  [       0.0%]   11 [       0.0%]   19 [       0.0%]   27 [       0.0%]
  4  [       0.0%]   12 [       0.0%]   20 [       0.0%]   28 [       0.0%]
  5  [       0.0%]   13 [       0.0%]   21 [|      1.3%]   29 [       0.0%]
  6  [       0.0%]   14 [       0.0%]   22 [       0.0%]   30 [|      0.6%]
  7  [       0.0%]   15 [       0.0%]   23 [       0.0%]   31 [       0.0%]
  8  [       0.0%]   16 [       0.0%]   24 [       0.0%]   32 [       0.0%]
  Mem[||||||||||||||||||||1.42G/252G]   Tasks: 188, 366 thr; 1 running
  Swp[|                   2.47G/256G]   Load average: 0.00 0.00 0.00
                                        Uptime: 432 days(!), 00:03:55

   PID USER      PRI  NI  VIRT   RES   SHR S CPU% MEM%   TIME+  Command
 9389 andrew     20   0 23344  3848  2848 R  1.3  0.0  0:00.10 htop
10103 root       20   0 3216M 17896  2444 S  0.7  0.0  5h48:56 /usr/bin/dockerd
    1 root       20   0  181M  4604  2972 S  0.0  0.0 15:29.66 /lib/systemd/syst
  533 root       20   0 44676  6908  6716 S  0.0  0.0 11:19.77 /lib/systemd/syst
  546 root       20   0  244M     0     0 S  0.0  0.0  0:01.39 /sbin/lvmetad -f
 1526 root       20   0  329M  2252  1916 S  0.0  0.0  0:00.00 /usr/sbin/ModemMa
 1544 root       20   0  329M  2252  1916 S  0.0  0.0  0:00.06 /usr/sbin/ModemMa
F1Help  F2Setup F3SearchF4FilterF5Tree  F6SortByF7Nice -F8Nice +F9Kill  F10Quit
</code></pre>
<p><a name="REPLs-software-versions"></a></p>
<h2>REPLs and Software Versions</h2>
<p><a name="REPLs"></a></p>
<h3>REPLs</h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>A <strong>REPL</strong> is a Read-Evaluate-Print Loop, similar to the command line, but usually used for particular programming languages.</p>
<p>You can open the Python REPL with the <code>python</code> command (and quit with the <code>quit()</code> function):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ python
Python 3.5.2 (default, Nov 12 2018, 13:43:14) ...
>>> quit()
</code></pre>
<p>Open the R REPL with the <code>R</code> command (and quit with the <code>q()</code> function):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ R
R version 3.5.2 (2018-12-20) --"Eggshell Igloo" ...
> q()
Save workspace image? [y/n/c]: n
</code></pre>
<p>Open the Scala REPL with the <code>scala</code> command (and quit with the <code>:quit</code> command):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ scala
Welcome to Scala 2.11.12 ...
scala> :quit
</code></pre>
<p>Open the Java REPL with the <code>jshell</code> command (and quit with the <code>/exit</code> command):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ jshell
| Welcome to JShell--Version 11.0.1 ...
jshell> /exit
</code></pre>
<p>Alternatively, you can exit any of these REPLs with ^d (Ctrl+d). ^d is the EOF (end of file) marker on Unix and signifies the end of input.</p>
<p><a name="version"></a></p>
<h3><code>-version / --version / -v</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>Most commands and programs have a <code>-version</code> or <code>--version</code> flag which gives the software version of that command or program. Most applications make this information easily available:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ls --version
ls (GNU coreutils) 8.25 ...

[ andrew@pc01 ~ ]$ ncdu -version
ncdu 1.11

[ andrew@pc01 ~ ]$ python --version
Python 3.5.2
</code></pre>
<p>...but some are less intuitive:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ sbt scalaVersion
...
[info] 2.12.4
</code></pre>
<p>Note that some programs use <code>-v</code> as a version flag, while others use <code>-v</code> to mean "verbose", which will run the application while printing lots of diagnostic or debugging information:</p>
<pre><code class="hljs language-bash">SCP(1)                    BSD General Commands Manual                   SCP(1)

NAME
     scp -- secure copy (remote file copy program)
...
-v      Verbose mode.  Causes scp and ssh(1) to print debugging messages
             about their progress.  This is helpful in debugging connection,
             authentication, and configuration problems.
...
</code></pre>
<p><a name="env-vars-aliases"></a></p>
<h2>Environment Variables and Aliases</h2>
<p><a name="env-vars"></a></p>
<h3>Environment Variables</h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><strong>Environment variables</strong> (sometimes shortened to "env vars") are persistent variables that can be created and used within your <code>bash</code> shell. They are defined with an equals sign (<code>=</code>) and used with a dollar sign (<code>$</code>). You can see all currently-defined env vars with <code>printenv</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ printenv
SPARK_HOME=/usr/local/spark
TERM=xterm
...
</code></pre>
<p>Set a new environment variable with an <code>=</code> sign (don't put any spaces before or after the <code>=</code>, though!):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ myvar=hello
</code></pre>
<p>Print a specific env var to the terminal with <code>echo</code> and a preceding <code>$</code> sign:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ echo $myvar
hello
</code></pre>
<p>Environment variables which contain spaces or other whitespace should be surrounded by quotes (<code>"..."</code>). Note that reassigning a value to an env var overwrites it without warning:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ myvar="hello, world!" &#x26;&#x26; echo $myvar
hello, world!
</code></pre>
<p>Env vars can also be defined using the <code>export</code> command. When defined this way, they will also be available to sub-processes (commands called from this shell):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ export myvar="another one" &#x26;&#x26; echo $myvar
another one
</code></pre>
<p>You can unset an environment variable by leaving the right-hand side of the <code>=</code> blank or by using the <code>unset</code> command:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ unset mynewvar

[ andrew@pc01 ~ ]$ echo $mynewvar
</code></pre>
<p><a name="aliases"></a></p>
<h3>Aliases</h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><strong>Aliases</strong> are similar to environment variables but are usually used in a different way -- to replace long commands with shorter ones:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 apidocs ]$ ls -l -a -h -t
total 220K
drwxr-xr-x 5 andrew andrew 4.0K Dec 21 12:37 .
-rw-r--r-- 1 andrew andrew 9.9K Dec 21 12:37 help-doc.html
-rw-r--r-- 1 andrew andrew 4.5K Dec 21 12:37 script.js
...

[ andrew@pc01 apidocs ]$ alias lc="ls -l -a -h -t"

[ andrew@pc01 apidocs ]$ lc
total 220K
drwxr-xr-x 5 andrew andrew 4.0K Dec 21 12:37 .
-rw-r--r-- 1 andrew andrew 9.9K Dec 21 12:37 help-doc.html
-rw-r--r-- 1 andrew andrew 4.5K Dec 21 12:37 script.js
...
</code></pre>
<p>You can remove an alias with <code>unalias</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 apidocs ]$ unalias lc

[ andrew@pc01 apidocs ]$ lc
The program 'lc' is currently not installed. ...
</code></pre>
<blockquote>
<p><strong>Bonus:</strong></p>
<p><a href="http://bit.ly/2TDG8Tx">Read about the subtle differences between environment variables and aliases here.</a></p>
<p><a href="http://bit.ly/2TG8X1A">Some programs, like <strong>git</strong>, allow you to define aliases specifically for that software.</a></p>
</blockquote>
<p><a name="basic-bash-scripting"></a></p>
<h2>Basic <code>bash</code> Scripting</h2>
<p><a name="bash-scripts"></a></p>
<h3><code>bash</code> Scripts</h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>bash</code> scripts (usually ending in <code>.sh</code>) allow you to automate complicated processes, packaging them into reusable functions. A <code>bash</code> script can contain any number of normal shell commands:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ echo "ls &#x26;&#x26; touch file &#x26;&#x26; ls" > ex.sh
</code></pre>
<p>A shell script can be executed with the <code>source</code> command or the <code>sh</code> command:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ source ex.sh
Desktop  Git  TEST  c  ex.sh  project  test
Desktop  Git  TEST  c  ex.sh  file  project  test
</code></pre>
<p>Shell scripts can be made executable with the <code>chmod</code> command (more on this later):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ echo "ls &#x26;&#x26; touch file2 &#x26;&#x26; ls" > ex2.sh

[ andrew@pc01 ~ ]$ chmod +x ex2.sh
</code></pre>
<p>An executable shell script can be run by preceding it with <code>./</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ./ex2.sh
Desktop  Git  TEST  c  ex.sh  ex2.sh  file  project  test
Desktop  Git  TEST  c  ex.sh  ex2.sh  file  file2  project  test
</code></pre>
<p>Long lines of code can be split by ending a command with <code>\</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ echo "for i in {1..3}; do echo \
> \"Welcome \$i times\"; done" > ex3.sh
</code></pre>
<p>Bash scripts can contain loops, functions, and more!</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ source ex3.sh
Welcome 1 times
Welcome 2 times
Welcome 3 times
</code></pre>
<p><a name="custom-prompt-ls"></a></p>
<h3>Custom Prompt and <code>ls</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>Bash scripting can make your life a whole lot easier and more colourful. <a href="https://devhints.io/bash">Check out this great bash scripting cheat sheet.</a></p>
<p><code>$PS1</code> (Prompt String 1) is the environment variable that defines your main shell prompt (<a href="http://bit.ly/2SPgsmT">learn about the other prompts here</a>):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ printf "%q" $PS1
$'\\n\\[\E[1m\\]\\[\E[30m\\]\\A'$'\\[\E[37m\\]|\\[\E[36m\\]\\u\\[\E[37m\\]@\\[\E[34m\\]\\h'$'\\[\E[32m\\]\\W\\[\E[37m\\]|'$'\\[\E(B\E[m\\]‘
</code></pre>
<p>You can change your default prompt with the <code>export</code> command:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ export PS1="\ncommand here> "

command here> echo $PS1
\ncommand here>
</code></pre>
<p>...<a href="http://bit.ly/2TMbEit">you can add colours, too!</a>:</p>
<pre><code class="hljs language-bash">command here> export PS1="\e[1;31m\nCODE: \e[39m"

# (this should be red, but it may not show up that way in Markdown)
CODE: echo $PS1
\e[1;31m\nCODE: \e[39m
</code></pre>
<p>You can also change the colours shown by <code>ls</code> by editing the <code>$LS_COLORS</code> environment variable:</p>
<pre><code class="hljs language-bash"># (again, these colours might not show up in Markdown)
CODE: ls
Desktop  Git  TEST  c  ex.sh  ex2.sh  ex3.sh  file  file2  project  test

CODE: export LS_COLORS='di=31:fi=0:ln=96:or=31:mi=31:ex=92‘

CODE: ls
Desktop  Git  TEST  c  ex.sh  ex2.sh  ex3.sh  file  file2  project  test
</code></pre>
<p><a name="config-files"></a></p>
<h2>Config Files</h2>
<p><a name="config-bashrc"></a></p>
<h3>Config Files / <code>.bashrc</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>If you tried the commands in the last section and logged out and back in, you may have noticed that your changes disappeared. <em>config</em> (configuration) files let you maintain settings for your shell or for a particular program every time you log in (or run that program). The main configuration file for a <code>bash</code> shell is the <code>~/.bashrc</code> file. Aliases, environment variables, and functions added to <code>~/.bashrc</code> will be available every time you log in. Commands in <code>~/.bashrc</code> will be run every time you log in.</p>
<p>If you edit your <code>~/.bashrc</code> file, you can reload it without logging out by using the <code>source</code> command:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ nano ~/.bashrc
</code></pre>
<p><em>...add the line <code>echo “~/.bashrc loaded!”</code> to the top of the file</em>...</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ source ~/.bashrc
~/.bashrc loaded!
</code></pre>
<p><em>...log out and log back in...</em></p>
<pre><code class="hljs language-bash">Last login: Fri Jan 11 10:29:07 2019 from 111.11.11.111
~/.bashrc loaded!

[ andrew@pc01 ~ ]
</code></pre>
<p><a name="types-of-shells"></a></p>
<h3>Types of Shells</h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><em>Login</em> shells are shells you log in to (where you have a username). <em>Interactive</em> shells are shells which accept commands. Shells can be login and interactive, non-login and non-interactive, or any other combination.</p>
<p>In addition to <code>~/.bashrc</code>, there are a few other scripts which are <code>sourced</code> by the shell automatically when you log in or log out. These are:</p>
<ul>
<li><code>/etc/profile</code></li>
<li><code>~/.bash_profile</code></li>
<li><code>~/.bash_login</code></li>
<li><code>~/.profile</code></li>
<li><code>~/.bash_logout</code></li>
<li><code>/etc/bash.bash_logout</code></li>
</ul>
<p>Which of these scripts are sourced, and the order in which they're sourced, depend on the type of shell opened. See <a href="https://linux.die.net/man/1/bash">the bash man page</a> and <a href="http://bit.ly/2TGCwA8">these</a> Stack Overflow <a href="http://bit.ly/2TFHFsf">posts</a> for more information.</p>
<p>Note that <code>bash</code> scripts can <code>source</code> other scripts. For instance, in your <code>~/.bashrc</code>, you could include the line:</p>
<pre><code class="hljs language-bash">source ~/.bashrc_addl
</code></pre>
<p>...which would also <code>source</code> that <code>.bashrc_addl</code> script. This file can contain its own aliases, functions, environment variables, and so on. It could, in turn, <code>source</code> other scripts, as well. (Be careful to avoid infinite loops of script-sourcing!)</p>
<p>It may be helpful to split commands into different shell scripts based on functionality or machine type (Ubuntu vs. Red Hat vs. macOS), for example:</p>
<ul>
<li><code>~/.bash_ubuntu</code> -- configuration specific to Ubuntu-based machines</li>
<li><code>~/.bashrc_styles</code> -- aesthetic settings, like <code>PS1</code> and <code>LS_COLORS</code></li>
<li><code>~/.bash_java</code> -- configuration specific to the Java language</li>
</ul>
<p>I try to keep separate <code>bash</code> files for aesthetic configurations and OS- or machine-specific code, and then I have one big <code>bash</code> file containing shortcuts, etc. that I use on every machine and every OS.</p>
<p>Note that there are also <em>different shells</em>. <code>bash</code> is just one kind of shell (the "Bourne Again Shell"). Other common ones include <code>zsh</code>, <code>csh</code>, <code>fish</code>, and more. Play around with different shells and find one that's right for you, but be aware that this tutorial contains <code>bash</code> shell commands only and not everything listed here (maybe none of it) will be applicable to shells other than <code>bash</code>.</p>
<p><a name="finding-things"></a></p>
<h2>Finding Things</h2>
<p><a name="whereis-which-whatis"></a></p>
<h3><code>whereis / which / whatis</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>whereis</code> searches for "possibly useful" files related to a particular command. It will attempt to return the location of the binary (executable machine code), source (code source files), and <code>man</code> page for that command:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ whereis ls
ls: /bin/ls /usr/share/man/man1/ls.1.gz
</code></pre>
<p><code>which</code> will only return the location of the binary (the command itself):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ which ls
/bin/ls
</code></pre>
<p><code>whatis</code> prints out the one-line description of a command from its <code>man</code> page:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ whatis whereis which whatis
whereis (1)          - locate the binary, source, and manual page files for a command
which (1)            - locate a command
whatis (1)           - display one-line manual page descriptions
</code></pre>
<p><code>which</code> is useful for finding the "original version" of a command which may be hidden by an alias:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ alias ls="ls -l"

# “original” ls has been “hidden” by the alias defined above
[ andrew@pc01 ~ ]$ ls
total 36
drwxr-xr-x 2 andrew andrew 4096 Jan  9 14:47 Desktop
drwxr-xr-x 4 andrew andrew 4096 Dec  6 10:43 Git
...

# but we can still call “original” ls by using the location returned by which
[ andrew@pc01 ~ ]$ /bin/ls
Desktop  Git  TEST  c  ex.sh  ex2.sh  ex3.sh  file  file2  project  test
</code></pre>
<p><a name="locate-find"></a></p>
<h3><code>locate / find</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>locate</code> finds a file anywhere on the system by referring to a semi-regularly-updated cached list of files:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ locate README.md
/home/andrew/.config/micro/plugins/gotham-colors/README.md
/home/andrew/.jenv/README.md
/home/andrew/.myshell/README.md
...
</code></pre>
<p>Because it's just searching a list, <code>locate</code> is usually faster than the alternative, <code>find</code>. <code>find</code> iterates through the file system to find the file you're looking for. Because it's actually looking at the files which <em>currently</em> exist on the system, though, it will always return an up-to-date list of files, which is not necessarily true with <code>locate</code>.</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ find ~/ -iname "README.md"
/home/andrew/.jenv/README.md
/home/andrew/.config/micro/plugins/gotham-colors/README.md
/home/andrew/.oh-my-zsh/plugins/ant/README.md
...
</code></pre>
<p><code>find</code> was written for the very first version of Unix in 1971, and is therefore much more widely available than <code>locate</code>, which was added to GNU in 1994.</p>
<p><code>find</code> has many more features than <code>locate</code>, and can search by file age, size, ownership, type, timestamp, permissions, depth within the file system; <code>find</code> can search using regular expressions, execute commands on files it finds, and more.</p>
<p>When you need a fast (but possibly outdated) list of files, or you’re not sure what directory a particular file is in, use <code>locate</code>. When you need an accurate file list, maybe based on something other than the files’ names, and you need to do something with those files, use <code>find</code>.</p>
<p><a name="downloading-things"></a></p>
<h2>Downloading Things</h2>
<p><a name="ping-wget-curl"></a></p>
<h3><code>ping / wget / curl</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>ping</code> attempts to open a line of communication with a network host. Mainly, it's used to check whether or not your Internet connection is down:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ping google.com
PING google.com (74.125.193.100) 56(84) bytes of data.
Pinging 74.125.193.100 with 32 bytes of data:
Reply from 74.125.193.100: bytes=32 time&#x3C;1ms TTL=64
...
</code></pre>
<p><code>wget</code> is used to easily download a file from the Internet:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ wget \
> http://releases.ubuntu.com/18.10/ubuntu-18.10-desktop-amd64.iso
</code></pre>
<p><code>curl</code> can be used just like <code>wget</code> (don’t forget the <code>--output</code> flag):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ curl \
> http://releases.ubuntu.com/18.10/ubuntu-18.10-desktop-amd64.iso \
> --output ubuntu.iso
</code></pre>
<p><code>curl</code> and <code>wget</code> have their own strengths and weaknesses. <code>curl</code> supports many more protocols and is more widely available than <code>wget</code>; <code>curl</code> can also send data, while <code>wget</code> can only receive data. <code>wget</code> can download files recursively, while <code>curl</code> cannot.</p>
<p>In general, I use <code>wget</code> when I need to download things from the Internet. I don’t often need to send data using <code>curl</code>, but it’s good to be aware of it for the rare occasion that you do.</p>
<p><a name="apt-gunzip-tar-gzip"></a></p>
<h3><code>apt / gunzip / tar / gzip</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>Debian-descended Linux distributions have a fantastic package management tool called <code>apt</code>. It can be used to install, upgrade, or delete software on your machine. To search <code>apt</code> for a particular piece of software, use <code>apt search</code>, and install it with <code>apt install</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ apt search bleachbit
...bleachbit/bionic,bionic 2.0-2 all
  delete unnecessary files from the system

# you need to 'sudo' to install software
[ andrew@pc01 ~ ]$ sudo apt install bleachbit
</code></pre>
<p>Linux software often comes packaged in <code>.tar.gz</code> ("tarball") files:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ wget \
> https://github.com/atom/atom/releases/download/v1.35.0-beta0/atom-amd64.tar.gz
</code></pre>
<p>...these types of files can be unzipped with <code>gunzip</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ gunzip atom-amd64.tar.gz &#x26;&#x26; ls
atom-amd64.tar
</code></pre>
<p>A <code>.tar.gz</code> file will be <code>gunzip</code>-ped to a <code>.tar</code> file, which can be extracted to a directory of files using <code>tar -xf</code> (<code>-x</code> for "extract", <code>-f</code> to specify the file to "untar"):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ tar -xf atom-amd64.tar &#x26;&#x26; mv \
atom-beta-1.35.0-beta0-amd64 atom &#x26;&#x26; ls
atom atom-amd64.tar
</code></pre>
<p>To go in the reverse direction, you can create (<code>-c</code>) a tar file from a directory and zip it (or unzip it, as appropriate) with <code>-z</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ tar -zcf compressed.tar.gz atom &#x26;&#x26; ls
atom  atom-amd64.tar  compressed.tar.gz
</code></pre>
<p><code>.tar</code> files can also be zipped with <code>gzip</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ gzip atom-amd64.tar &#x26;&#x26; ls
atom  atom-amd64.tar.gz compressed.tar.gz
</code></pre>
<p><a name="redirecting-io"></a></p>
<h2>Redirecting Input and Output</h2>
<p><a name="pipe-gt-lt-echo-printf"></a></p>
<h3><code>| / > / &#x3C; / echo / printf</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>By default, shell commands read their input from the standard input stream (aka. stdin or 0) and write to the standard output stream (aka. stdout or 1), unless there’s an error, which is written to the standard error stream (aka. stderr or 2).</p>
<p><code>echo</code> writes text to stdout by default, which in most cases will simply print it to the terminal:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ echo "hello"
hello
</code></pre>
<p>The pipe operator, <code>|</code>, redirects the output of the first command to the input of the second command:</p>
<pre><code class="hljs language-bash"># 'wc' (word count) returns the number of lines, words, bytes in a file
[ andrew@pc01 ~ ]$ echo "example document" | wc
      1       2      17
</code></pre>
<p><code>></code> redirects output from stdout to a particular location</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ echo "test" > file &#x26;&#x26; head file
test
</code></pre>
<p><code>printf</code> is an improved <code>echo</code>, allowing formatting and escape sequences:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ printf "1\n3\n2"
1
3
2
</code></pre>
<p><code>&#x3C;</code> gets input from a particular location, rather than stdin:</p>
<pre><code class="hljs language-bash"># 'sort' sorts the lines of a file alphabetically / numerically
[ andrew@pc01 ~ ]$ sort &#x3C;(printf "1\n3\n2")
1
2
3
</code></pre>
<p>Rather than a <a href="#viewing-and-editing-files">UUOC</a>, the recommended way to send the contents of a file to a command is to use <code>&#x3C;</code>. Note that this causes data to "flow" right-to-left on the command line, rather than (the perhaps more natural, for English-speakers) left-to-right:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ printf "1\n3\n2" > file &#x26;&#x26; sort &#x3C; file
1
2
3
</code></pre>
<p><a name="std-tee"></a></p>
<h3><code>0 / 1 / 2 / tee</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>0, 1, and 2 are the standard input, output, and error streams, respectively. Input and output streams can be redirected with the <code>|</code>, <code>></code>, and <code>&#x3C;</code> operators mentioned previously, but stdin, stdout, and stderr can also be manipulated directly using their numeric identifiers:</p>
<p>Write to stdout or stderr with <code>>&#x26;1</code> or <code>>&#x26;2</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ cat test
echo "stdout" >&#x26;1
echo "stderr" >&#x26;2
</code></pre>
<p>By default, stdout and stderr both print output to the terminal:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ./test
stderr
stdout
</code></pre>
<p>Redirect stdout to <code>/dev/null</code> (only print output sent to stderr):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ./test 1>/dev/null
stderr
</code></pre>
<p>Redirect stderr to <code>/dev/null</code> (only print output sent to stdout):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ./test 2>/dev/null
stdout
</code></pre>
<p>Redirect all output to <code>/dev/null</code> (print nothing):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ./test &#x26;>/dev/null
</code></pre>
<p>Send output to stdout and any number of additional locations with <code>tee</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ls &#x26;&#x26; echo "test" | tee file1 file2 file3 &#x26;&#x26; ls
file0
test
file0  file1  file2  file3
</code></pre>
<h1><a name="advanced">Advanced</a></h1>
<h2><a name="superuser">Superuser</a></h2>
<p><a name="sudo-su"></a></p>
<h3><code>sudo / su</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>You can check what your username is with <code>whoami</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 abc ]$ whoami
andrew
</code></pre>
<p>...and run a command as another user with <code>sudo -u username</code> (you will need that user's password):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 abc ]$ sudo -u test touch def &#x26;&#x26; ls -l
total 0
-rw-r--r-- 1 test test 0 Jan 11 20:05 def
</code></pre>
<p>If <code>–u</code> is not provided, the default user is the superuser (usually called "root"), with unlimited permissions:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 abc ]$ sudo touch ghi &#x26;&#x26; ls -l
total 0
-rw-r--r-- 1 test test 0 Jan 11 20:05 def
-rw-r--r-- 1 root root 0 Jan 11 20:14 ghi
</code></pre>
<p>Use <code>su</code> to become another user temporarily (and <code>exit</code> to switch back):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 abc ]$ su test
Password:
test@pc01:/home/andrew/abc$ whoami
test
test@pc01:/home/andrew/abc$ exit
exit

[ andrew@pc01 abc ]$ whoami
andrew
</code></pre>
<p><a href="http://bit.ly/2SKQH77">Learn more about the differences between <code>sudo</code> and <code>su</code> here.</a></p>
<p><a name="click-click"></a></p>
<h3><code>!!</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>The superuser (usually "root") is the only person who can install software, create users, and so on. Sometimes it's easy to forget that, and you may get an error:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ apt install ruby
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
</code></pre>
<p>You could retype the command and add <code>sudo</code> at the front of it (run it as the superuser):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ sudo apt install ruby
Reading package lists...
</code></pre>
<p>Or, you could use the <code>!!</code> shortcut, which retains the previous command:</p>
<pre><code>[ andrew@pc01 ~ ]$ apt install ruby
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?

[ andrew@pc01 ~ ]$ sudo !!
sudo apt install ruby
Reading package lists...
</code></pre>
<p>By default, running a command with <code>sudo</code> (and correctly entering the password) allows the user to run superuser commands for the next 15 minutes. Once those 15 minutes are up, the user will again be prompted to enter the superuser password if they try to run a restricted command.</p>
<p><a name="file-permissions"></a></p>
<h2>File Permissions</h2>
<p><a name="file-permissions-sub"></a></p>
<h3>File Permissions</h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>Files may be able to be read (<code>r</code>), written to (<code>w</code>), and/or executed (<code>x</code>) by different users or groups of users, or not at all. File permissions can be seen with the <code>ls -l</code> command and are represented by 10 characters:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ls -lh
total 8
drwxr-xr-x 4 andrew andrew 4.0K Jan  4 19:37 tast
-rwxr-xr-x 1 andrew andrew   40 Jan 11 16:16 test
-rw-r--r-- 1 andrew andrew    0 Jan 11 16:34 tist
</code></pre>
<p>The first character of each line represents the type of file, (<code>d</code> = directory, <code>l</code> = link, <code>-</code> = regular file, and so on); then there are three groups of three characters which represent the permissions held by the user (u) who owns the file, the permissions held by the group (g) which owns the file, and the permissions held any other (o) users. (The number which follows this string of characters is the number of links in the file system to that file (4 or 1 above).)</p>
<p><code>r</code> means that person / those people have read permission, <code>w</code> is write permission, <code>x</code> is execute permission. If a directory is “executable”, that means it can be opened and its contents can be listed. These three permissions are often represented with a single three-digit number, where, if <code>x</code> is enabled, the number is incremented by 1, if <code>w</code> is enabled, the number is incremented by 2, and if <code>r</code> is enabled, the number is incremented by 4. Note that these are equivalent to binary digits (<code>r-x</code> -> <code>101</code> -> <code>5</code>, for example). So the above three files have permissions of 755, 755, and 644, respectively.</p>
<p>The next two strings in each list are the name of the owner (<code>andrew</code>, in this case) and the group of the owner (also <code>andrew</code>, in this case). Then comes the size of the file, its most recent modification time, and its name. The <code>–h</code> flag makes the output human readable (i.e. printing <code>4.0K</code> instead of <code>4096</code> bytes).</p>
<p><a name="chmod-chown"></a></p>
<h3><code>chmod / chown</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>File permissions can be modified with <code>chmod</code> by setting the access bits:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ chmod 777 test &#x26;&#x26; chmod 000 tist &#x26;&#x26; ls -lh
total 8.0K
drwxr-xr-x 4 andrew andrew 4.0K Jan  4 19:37 tast
-rwxrwxrwx 1 andrew andrew   40 Jan 11 16:16 test
---------- 1 andrew andrew    0 Jan 11 16:34 tist
</code></pre>
<p>...or by adding (<code>+</code>) or removing (<code>-</code>) <code>r</code>, <code>w</code>, and <code>x</code> permissions with flags:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ chmod +rwx tist &#x26;&#x26; chmod -w test &#x26;&#x26; ls -lh
chmod: test: new permissions are r-xrwxrwx, not r-xr-xr-x
total 8.0K
drwxr-xr-x 4 andrew andrew 4.0K Jan  4 19:37 tast
-r-xrwxrwx 1 andrew andrew   40 Jan 11 16:16 test
-rwxr-xr-x 1 andrew andrew    0 Jan 11 16:34 tist
</code></pre>
<p>The user who owns a file can be changed with <code>chown</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ sudo chown marina test
</code></pre>
<p>The group which owns a file can be changed with <code>chgrp</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ sudo chgrp hadoop tist &#x26;&#x26; ls -lh
total 8.0K
drwxr-xr-x 4 andrew andrew 4.0K Jan  4 19:37 tast
-----w--w- 1 marina andrew   40 Jan 11 16:16 test
-rwxr-xr-x 1 andrew hadoop    0 Jan 11 16:34 tist
</code></pre>
<p><a name="users-groups"></a></p>
<h2>User and Group Management</h2>
<p><a name="users"></a></p>
<h3>Users</h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>users</code> shows all users currently logged in. Note that a user can be logged in multiple times if -- for instance -- they're connected via multiple <code>ssh</code> sessions.</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ users
andrew colin colin colin colin colin krishna krishna
</code></pre>
<p>To see all users (even those not logged in), check <code>/etc/passwd</code>. (<strong>WARNING</strong>: do not modify this file! You can corrupt your user accounts and make it impossible to log in to your system.)</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ alias au="cut -d: -f1 /etc/passwd \
> | sort | uniq" &#x26;&#x26; au
 _apt
anaid
andrew...
</code></pre>
<p>Add a user with <code>useradd</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ sudo useradd aardvark &#x26;&#x26; au
_apt
aardvark
anaid...
</code></pre>
<p>Delete a user with <code>userdel</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ sudo userdel aardvark &#x26;&#x26; au
_apt
anaid
andrew...
</code></pre>
<p><a href="http://bit.ly/2D4upIg">Change a user’s default shell, username, password, or group membership with <code>usermod</code>.</a></p>
<p><a name="groups"></a></p>
<h3>Groups</h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>groups</code> shows all of the groups of which the current user is a member:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ groups
andrew adm cdrom sudo dip plugdev lpadmin sambashare hadoop
</code></pre>
<p>To see all groups on the system, check <code>/etc/group</code>. (<strong>DO NOT MODIFY</strong> this file unless you know what you are doing.)</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ alias ag=“cut -d: -f1 /etc/group \
> | sort” &#x26;&#x26; ag
adm
anaid
andrew...
</code></pre>
<p>Add a group with <code>groupadd</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ sudo groupadd aardvark &#x26;&#x26; ag
aardvark
adm
anaid...
</code></pre>
<p>Delete a group with <code>groupdel</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ sudo groupdel aardvark &#x26;&#x26; ag
adm
anaid
andrew...
</code></pre>
<p><a href="https://linux.die.net/man/8/groupmod">Change a group’s name, ID number, or password with <code>groupmod</code>.</a></p>
<p><a name="text-processing"></a></p>
<h2>Text Processing</h2>
<p><a name="uniq-sort-diff-cmp"></a></p>
<h3><code>uniq / sort / diff / cmp</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>uniq</code> can print unique lines (default) or repeated lines:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 man ]$ printf "1\n2\n2" > a &#x26;&#x26; \> printf "1\n3\n2" > b

[ andrew@pc01 man ]$ uniq a
1
2
</code></pre>
<p><code>sort</code> will sort lines alphabetically / numerically:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 man ]$ sort b
1
2
3
</code></pre>
<p><code>diff</code> will report which lines differ between two files:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 man ]$ diff a b
2c2
&#x3C; 2
---
> 3
</code></pre>
<p><code>cmp</code> reports which bytes differ between two files:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 man ]$ cmp a b
a b differ: char 3, line 2
</code></pre>
<p><a name="cut-sed"></a></p>
<h3><code>cut / sed</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>cut</code> is usually used to cut a line into sections on some delimiter (good for CSV processing). <code>-d</code> specifies the delimiter and <code>-f</code> specifies the field index to print (starting with 1 for the first field):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 man ]$ printf "137.99.234.23" > c

[ andrew@pc01 man ]$ cut -d'.' c -f1
137
</code></pre>
<p><code>sed</code> is commonly used to replace a string with another string in a file:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 man ]$ echo "old" | sed s/old/new/
new
</code></pre>
<p>...but <code>sed</code> is an extremely powerful utility, and cannot be properly summarised here. It’s actually Turing-complete, so it can do anything that any other programming language can do. <code>sed</code> can find and replace based on regular expressions, selectively print lines of a file which match or contain a certain pattern, edit text files in-place and non-interactively, and much more.</p>
<p>A few good tutorials on <code>sed</code> include:</p>
<ul>
<li><a href="https://www.tutorialspoint.com/sed/">https://www.tutorialspoint.com/sed/</a></li>
<li><a href="http://www.grymoire.com/Unix/Sed.html">http://www.grymoire.com/Unix/Sed.html</a></li>
<li><a href="https://www.computerhope.com/unix/used.htm">https://www.computerhope.com/unix/used.htm</a></li>
</ul>
<p><a name="pattern-matching"></a></p>
<h2>Pattern Matching</h2>
<p><a name="grep"></a></p>
<h3><code>grep</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>The name <code>grep</code> comes from <code>g</code>/<code>re</code>/<code>p</code> (search <code>g</code>lobally for a <code>r</code>egular <code>e</code>xpression and <code>p</code>rint it); it’s used for finding text in files.</p>
<p><code>grep</code> is used to find lines of a file which match some pattern:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ grep -e ".*fi.*" /etc/profile
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
    # The file bash.bashrc already sets the default PS1.
    fi
    fi
...
</code></pre>
<p>...or contain some word:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ grep "andrew" /etc/passwd
andrew:x:1000:1000:andrew,,,:/home/andrew:/bin/bash
</code></pre>
<p><code>grep</code> is usually the go-to choice for simply finding matching lines in a file, if you’re planning on allowing some other program to handle those lines (or if you just want to view them).</p>
<p><code>grep</code> allows for (<code>-E</code>) use of extended regular expressions, (<code>-F</code>) matching any one of multiple strings at once, and (<code>-r</code>) recursively searching files within a directory. These flags used to be implemented as separate commands (<code>egrep</code>, <code>fgrep</code>, and <code>rgrep</code>, respectively), but those commands are now deprecated.</p>
<blockquote>
<p><strong>Bonus</strong>: <a href="https://kb.iu.edu/d/abnd">see the origins of the names of a few famous <code>bash</code> commands</a></p>
</blockquote>
<p><a name="awk"></a></p>
<h3><code>awk</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>awk</code> is a pattern-matching language built around reading and manipulating delimited data files, like CSV files.</p>
<p>As a rule of thumb, <code>grep</code> is good for finding strings and patterns in files, <code>sed</code> is good for one-to-one replacement of strings in files, and <code>awk</code> is good for extracting strings and patterns from files and analysing them.</p>
<p>As an example of what <code>awk</code> can do, here’s a file containing two columns of data:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ printf "A 10\nB 20\nC 60" > file
</code></pre>
<p>Loop over the lines, add the number to sum, increment count, print the average:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ awk 'BEGIN {sum=0; count=0; OFS=" "} {sum+=$2; count++} END {print "Average:", sum/count}' file
Average: 30
</code></pre>
<p><code>sed</code> and <code>awk</code> are both Turing-complete languages. There have been multiple books written about each of them. They can be extremely useful with pattern matching and text processing. I really don’t have enough space here to do either of them justice. Go read more about them!</p>
<blockquote>
<p><strong>Bonus</strong>: <a href="http://bit.ly/2AI3IaN">learn about some of the differences between <code>sed</code>, <code>grep</code>, and <code>awk</code></a></p>
</blockquote>
<p><a name="ssh"></a></p>
<h2>Copying Files Over <code>ssh</code></h2>
<p><a name="ssh-scp"></a></p>
<h3><code>ssh / scp</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>ssh</code> is how Unix-based machines connect to each other over a network:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ssh –p &#x3C;port> andrew@137.xxx.xxx.89
Last login: Fri Jan 11 12:30:52 2019 from 137.xxx.xxx.199
</code></pre>
<p>Notice that my prompt has changed as I’m now on a different machine:</p>
<pre><code class="hljs language-bash">[ andrew@pc02 ~ ]$ exit
logout
Connection to 137.xxx.xxx.89 closed.
</code></pre>
<p>Create a file on machine 1:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ echo "hello" > hello
</code></pre>
<p>Copy it to machine 2 using <code>scp</code> (secure copy; note that <code>scp</code> uses <code>–P</code> for a port #, <code>ssh</code> uses <code>–p</code>)</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ scp –P &#x3C;port> hello andrew@137.xxx.xxx.89:~
hello                                         100%    0     0.0KB/s   00:00
</code></pre>
<p><code>ssh</code> into machine 2:</p>
<pre><code class="hljs language-bash">[ andrew@pc02 ~ ]$ ssh –p &#x3C;port> andrew@137.xxx.xxx.89
Last login: Fri Jan 11 22:47:37 2019 from 137.xxx.xxx.79
</code></pre>
<p>The file’s there!</p>
<pre><code class="hljs language-bash">[ andrew@pc02 ~ ]$ ls
hello  multi  xargs

[ andrew@pc02 ~ ]$ cat hello
hello
</code></pre>
<p><a name="rsync"></a></p>
<h3><code>rsync</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>rsync</code> is a file-copying tool which minimises the amount of data copied by looking for deltas (changes) between files.</p>
<p>Suppose we have two directories: <code>d</code>, with one file, and <code>s</code>, with two files:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 d ]$ ls &#x26;&#x26; ls ../s
f0
f0  f1
</code></pre>
<p>Sync the directories (copying only missing data) with <code>rsync</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 d ]$ rsync -av ../s/* .
sending incremental file list...
</code></pre>
<p><code>d</code> now contains all files that <code>s</code> contains:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 d ]$ ls
f0  f1
</code></pre>
<p><code>rsync</code> can be performed over <code>ssh</code> as well:</p>
<pre><code class="hljs language-bash">[ andrew@pc02 r ]$ ls

[ andrew@pc02 r ]$ rsync -avz -e "ssh -p &#x3C;port>" andrew@137.xxx.xxx.79:~/s/* .
receiving incremental file list
f0
f1

sent 62 bytes  received 150 bytes  141.33 bytes/sec
total size is 0  speedup is 0.00

[ andrew@pc02 r ]$ ls
f0  f1
</code></pre>
<p><a name="long-running-processes"></a></p>
<h2>Long-Running Processes</h2>
<p><a name="yes-nohup-ps-kill"></a></p>
<h3><code>yes / nohup / ps / kill</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>Sometimes, <code>ssh</code> connections can disconnect due to network or hardware problems. Any processes initialized through that connection will be “hung up” and terminate. Running a command with <code>nohup</code> insures that the command will not be hung up if the shell is closed or if the network connection fails.</p>
<p>Run <code>yes</code> (continually outputs "y" until it’s killed) with <code>nohup</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ nohup yes &#x26;
[1] 13173
</code></pre>
<p><code>ps</code> shows a list of the current user’s processes (note PID number 13173):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ps | sed -n '/yes/p'
13173 pts/10   00:00:12 yes
</code></pre>
<p><em>...log out and log back into this shell...</em></p>
<p>The process has disappeared from <code>ps</code>!</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ ps | sed -n '/yes/p'

</code></pre>
<p>But it still appears in <code>top</code> and <code>htop</code> output:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ top -bn 1 | sed -n '/yes/p'
13173 andrew    20   0    4372    704    636 D  25.0  0.0   0:35.99 yes
</code></pre>
<p>Kill this process with <code>-9</code> followed by its process ID (PID) number:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ kill -9 13173
</code></pre>
<p>It no longer appears in <code>top</code>, because it’s been killed:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ top -bn 1 | sed -n '/yes/p'

</code></pre>
<p><a name="cron"></a></p>
<h3><code>cron / crontab / >></code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>cron</code> provides an easy way of automating regular, scheduled tasks.</p>
<p>You can edit your <code>cron</code> jobs with <code>crontab –e</code> (opens a text editor). Append the line:</p>
<pre><code>* * * * * date >> ~/datefile.txt
</code></pre>
<p>This will run the <code>date</code> command every minute, appending (with the <code>>></code> operator) the output to a file:</p>
<pre><code class="hljs language-bash">[ andrew@pc02 ~ ]$ head ~/datefile.txt
Sat Jan 12 14:37:01 GMT 2019
Sat Jan 12 14:38:01 GMT 2019
Sat Jan 12 14:39:01 GMT 2019...
</code></pre>
<p>Just remove that line from the <code>crontab</code> file to stop the job from running. <code>cron</code> jobs can be set up to run at particular minutes of each hour (0-59), particular hours of each day (0-23), particular days of each month (1-31), particular months of each year (1-12), or particular days of each week (0-6, Sun-Sat). This is what the five stars at the beginning of the command above represent, respectively. Replace them with specific numbers to run them on particular days or at particular times.</p>
<p>If a job is to be run irrespective of, for instance, the day of the week, then the position that represents the day of the week (the 5th position) should contain a star (<code>*</code>). This is why the command above runs every minute (the smallest interval available). <code>cron</code> jobs can be set up to run only when the system is rebooted, with <code>@reboot</code> replacing the stars/numbers. Jobs can also be run a specific number of times per hour or day or at multiple specific times per hour / day / week / month / etc.</p>
<p><a href="http://bit.ly/2FxIr75">Check out this tutorial for more info.</a></p>
<p><a name="advanced-misc"></a></p>
<h2>Miscellaneous</h2>
<p><a name="pushd-popd"></a></p>
<h3><code>pushd / popd</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p>Use <code>pushd</code> and <code>popd</code> to maintain a directory stack, instead of <code>cd</code>-ing everywhere.</p>
<p>Start in the <code>home</code> directory -- this will be the bottom directory in our “stack”:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ pwd
/home/andrew
</code></pre>
<p>Move to this directory with a long name, “push” it onto the stack with <code>pushd</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ pushd /etc/java/security/security.d/
/etc/java/security/security.d ~
</code></pre>
<p>Move to a third directory and add it to the stack:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 security.d ]$ pushd ~/test/
~/test /etc/java/security/security.d ~
</code></pre>
<p>When a new directory is added to the stack, it is added to the left-hand side of the list printed by <code>pushd</code>. To "pop" the top directory off (return to the most recent directory we added), we can use the <code>popd</code> command.</p>
<p>“Pop” off the top directory, move to the next one down the stack with <code>popd</code>:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 test ]$ popd
/etc/java/security/security.d ~

[ andrew@pc01 security.d ]$ pwd
/etc/java/security/security.d
</code></pre>
<p>Pop another directory off the stack and we’ve back to where we started:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 security.d ]$ popd
~

[ andrew@pc01 ~ ]$ pwd
/home/andrew
</code></pre>
<p><a name="xdg-open"></a></p>
<h3><code>xdg-open</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>xdg-open</code> opens a file with the default application (which could be a GUI program). It's a really useful tool for opening HTML documents from the command line. It's the Unix equivalent of macOS's <code>open</code> command:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 security.d ]$ xdg-open index.html
</code></pre>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/ftg29mpjtru1o5vs3pzv.png" alt=""></p>
<p><a name="xargs"></a></p>
<h3><code>xargs</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>xargs</code> vectorises commands, running them over any number of arguments in a loop.</p>
<p><code>ls</code> this directory, its parent directory, and its grandparent directory:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ export lv=".\n..\n../.."

[ andrew@pc01 ~ ]$ printf $lv | xargs ls
.:
multi  file

..:
anaid  andrew  colin...

../..:
bin    dev   index...
</code></pre>
<p>Arguments can be run through a chain of commands with the <code>–I</code> flag.</p>
<p><code>pwd</code> this directory, its parent directory, and its grandparent directory by <code>cd</code>-ing into each directory first:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ printf $lv | xargs -I % sh -c 'cd %; pwd %'
/home/andrew
/home
/
</code></pre>
<p><a href="https://shapeshed.com/unix-xargs/">Here’s a great tutorial on xargs.</a></p>
<p><a name="bonus"></a></p>
<h1>Bonus: Fun But Mostly Useless Things</h1>
<p><a name="w-write-wall-lynx"></a></p>
<h3><code>w / write / wall / lynx</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>w</code> is a more detailed <code>who</code>, showing who’s logged in and what they’re doing:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ w
 17:32:42 up 434 days,  3:11,  8 users,  load average: 2.32, 2.46, 2.57
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
colin    pts/9    137.xx.xx.210    03Jan19  5:28m  1:12   0.00s sshd: colin [priv]
andrew   pts/10   137.xx.xx.199    11:05    1.00s  0.15s  0.04s sshd: andrew [priv]
colin    pts/12   137.xx.xx.210    03Jan19 34:32   1.59s  1.59s –bash
...
</code></pre>
<p><code>write</code> sends a message to a specific user:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ echo "hello" | write andrew pts/10

Message from andrew@pc01 on pts/10 at 17:34 ...
hello
EOF
</code></pre>
<p><code>wall</code> is similar to <code>write</code>, but it sends the same message to every logged-in user. <code>write</code> and <code>wall</code> used to be more useful before email, Twitter, WhatsApp and instant messaging.</p>
<p><code>lynx</code> is a fully-functional, text-based web browser:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/qgr62yiukzj0skkbe5az.png" alt=""></p>
<p><a name="nautilus-date-cal-bc"></a></p>
<h3><code>nautilus / date / cal / bc</code></h3>
<p><a href="#toc">[ Back to Table of Contents ]</a></p>
<p><code>nautilus</code> initialises a GUI remote desktop session and opens a file browser.</p>
<p><code>date</code> shows the current date and time:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ date
Fri Jan 11 17:40:30 GMT 2019
</code></pre>
<p><code>cal</code> shows an ASCII calendar of this month with today’s date highlighted:</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ cal
    January 2019
Su Mo Tu We Th Fr Sa
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
</code></pre>
<p><code>bc</code> is a basic arithmetic calculator (use Python instead):</p>
<pre><code class="hljs language-bash">[ andrew@pc01 ~ ]$ bc
bc 1.06.95 ...
20/4
5
</code></pre>
<hr>
<p>That's it for now! Let me know if you know of any extra features or cool commands I should add to this list. Also, please let me know if you find any typos or misinformation. I've tried my best to check everything, but there's a lot here!</p>
<p>If you enjoyed this post, please consider supporting my work by <a href="https://ko-fi.com/Z8Z811E9B">buying me a coffee</a>!</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
        <item>
            <title><![CDATA[Managing Your Python Project with Git and PyBuilder]]></title>
            <link>https://awwsmm.com/blog/managing-your-python-project-with-git-and-pybuilder</link>
            <guid isPermaLink="false">managing-your-python-project-with-git-and-pybuilder</guid>
            <pubDate>Tue, 25 Sep 2018 00:00:00 GMT</pubDate>
            <description><![CDATA[Maintain control of your code!]]></description>
            <content:encoded><![CDATA[<div class="processed-markdown"><blockquote>
<p>Originally posted on <a href="https://dev.to/awwsmm/managing-your-python-project-with-git-and-pybuilder-21if">Dev.To</a></p>
</blockquote>
<h1>Introduction</h1>
<p>Most of my recent work has been in Java, a language which offers lots of project management tools. The most famous of these is probably <a href="https://maven.apache.org/index.html">Maven</a>. Maven helps you to keep your code and dependencies organized, and makes it easy to compile and package your code.</p>
<p>Maybe it's because Java tends to be a much more verbose language (and therefore needs special tools to help wrangle it into submission), or maybe it's because lots of people use Python for small scripts and helper functions, but I've struggled to find a Maven-like program to use when I'm coding in Python. Recently, I put some effort into getting a new Python project organized and I've found what I think is the best solution for managing a large Python project: PyBuilder + Git.</p>
<h2>PyBuilder</h2>
<p><a href="http://pybuilder.github.io/">PyBuilder</a> is a project management tool meant primarily for Python. It organizes your code with a consistent directory structure (for source code, scripts, and tests), manages unit testing and code coverage, and can package your code for easy sharing or uploading to the Python Package Index (<a href="https://pypi.org/">PyPI</a>). Using <a href="https://docs.python.org/3/library/pydoc.html">pydoc</a>, we can also add proper documentation to the list of available features. A full introduction to PyBuilder can be found <a href="http://pybuilder.github.io/documentation/tutorial.html">here</a>.</p>
<h2>Git</h2>
<p><a href="https://git-scm.com/">Git</a> is probably the most popular version control system (VCS) available today. By managing version control through a pseudo-filesystem, rather than the delta-based approach of other VCSes, every copy ("clone") of a Git project is a complete backup of all code committed to that repository. Distributed VCSes like Git are also supremely resistant to intentional falsification and hardware failures, and allow for extremely flexible collaborative environments. A full introduction to Git can be found <a href="https://git-scm.com/book/en/v2">here</a>.</p>
<h2>Why both?</h2>
<p>Git doesn't care what your project looks like. It could have a very rigid directory structure, or it could be a directory full of GBs of cat memes. By combining the organizational power and project management of PyBuilder with the version control of Git, we get a Python project that is easy to navigate, easy to manage, and easy to dive into and start contributing to.</p>
<p>Note that both PyBuilder and Git could (and do) have books written about them. This tutorial is not meant to be an exhaustive introduction to either piece of software, but is meant more for someone who is trying to organize their Python project, has some familiarity with Git, and has a desire to ignore all of the pitfalls that I fell into to get to this point. Let's go!</p>
<h1>Setting up Git</h1>
<p>Before we install PyBuilder, we have to set up Git. I'm running this tutorial on a clean, minimal-install <a href="https://www.ubuntu.com/download/desktop">Ubuntu (18.04.1 LTS)</a> VM, so I'll do everything from scratch.</p>
<h2>Installing Git</h2>
<p>To find out if you have Git installed already (if you forgot or if you're on a new system), run the command</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~$ whereis git
</code></pre>
<p>If you have Git installed, this should return something like</p>
<pre><code>git: /usr/bin/git /use/share/man/man1/git.1.gz
</code></pre>
<p>My new VM doesn't have Git installed, so we'll start there. Ubuntu is a Debian-based Unix-like OS, so it has the Advanced Packaging Tool, <code>apt</code>. Git can be installed easily on Ubuntu via <code>apt</code>:</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~$ sudo apt-get install git
</code></pre>
<p>And we can verify the installation by getting the Git version:</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~$ git --version
git version 2.17.1
</code></pre>
<h2>Setting Up a New Git Repository</h2>
<p>Git repositories can be <em>cloned</em> -- that is, copied from an existing repository -- or created from scratch. For this tutorial, I'll assume you have some Python code on your computer that you want to assemble into a new Git repository. To do that, let's first make a directory where all the code will live, and then <code>init</code>ialize a new git repo:</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~$ mkdir MyProject
andrew@ubuntuvm:~$ cd MyProject
andrew@ubuntuvm:~/MyProject$ git init
Initialized empty git repository in /home/andrew/MyProject/.git
</code></pre>
<p>The <code>.git/</code> directory contains all of the information that Git needs to manage your files:</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~/MyProject$ sudo apt-get install tree 
andrew@ubuntuvm:~/MyProject$ tree .git/

.git/
|-- HEAD
|-- branches
|-- config
|-- description
|-- hooks
|   |-- applypatch-msg.sample
|   |-- commit-msg.sample
|   |-- post-update.sample
|   |-- pre-applypatch.sample
|   |-- pre-commit.sample
|   |-- pre-push.sample
|   |-- pre-rebase.sample
|   |-- prepare-commit-msg.sample
|   `-- update.sample
|-- info
|   `-- exclude
|-- objects
|   |-- info
|   `-- pack
`-- refs
    |-- heads
    `-- tags
</code></pre>
<p>But most of the time, you won't need to worry about what's in there, you can interact with Git through <code>git</code> commands. Before we learn about those, though, let's get our project organized with PyBuilder.</p>
<h1>Setting up PyBuilder</h1>
<p>The recommended way to use PyBuilder is to install it using <a href="https://pypi.org/project/pip/">pip</a>, and within a virtual environment. First, let's set up the virtual environment.</p>
<h2>Setting up a Virtual Environment</h2>
<p>Since I'm running this tutorial on an Ubuntu system, I already have Python installed (and I'm assuming you do, too, since you're reading this tutorial about how to organize your Python project). If you don't, the <a href="https://www.python.org/downloads/">Python Software Foundation</a> has instructions on how to download Python so you can use it on your system.</p>
<p>The next step involves a tool called <code>pip</code>, which is <a href="https://www.makeuseof.com/tag/install-pip-for-python/">installed differently on different OSes and different versions of Python</a>. In my case, I'm going to install <code>pip</code> with the command:</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~/MyProject$ sudo apt-get install python3-pip
</code></pre>
<p>...and then make sure pip is up-to-date with:</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~/MyProject$ python3 -m pip install --user --upgrade pip
</code></pre>
<p>Note that I'm using the <code>python3</code> command and not <code>python</code>, since Ubuntu 18 is set up to use Python 3.6.6 by default. Next, I can use pip to install <code>virtualenv</code>:</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~/MyProject$ python3 -m pip install --user virtualenv
</code></pre>
<p>If you get a warning like</p>
<pre><code>The script virtualenv is installed in `/home/andrew/.local/bin` which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
</code></pre>
<p>You can address this issue by adding the noted location to your system's <code>$PATH</code> variable:</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~/MyProject$ export PATH=$PATH:/home/andrew/.local/bin
andrew@ubuntuvm:~/MyProject$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:
/usr/local/games:/snap/bin:/home/andrew/.local/bin
</code></pre>
<p>Finally, create a virtual environment with</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~/MyProject$ virtualenv env
</code></pre>
<p>This simply creates the <code>env</code> directory within the <code>MyProject</code> directory. You can enter the virtual environment with the command</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~/MyProject$ source env/bin/activate
(env) andrew@ubuntuvm:~/MyProject$ 
</code></pre>
<p>The <code>(env)</code> before the command prompt indicates that you're within the virtual environment. You can exit the virtual environment at any time with the command</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ deactivate
andrew@ubuntuvm:~/MyProject$ 
</code></pre>
<p>Note that <code>(env)</code> no longer appears at the beginning of the command prompt.</p>
<h2>Installing PyBuilder</h2>
<p>PyBuilder is really easy to install. Enter the virtual environment and <code>pip install</code>:</p>
<pre><code class="hljs language-shell">andrew@ubuntuvm:~/MyProject$ source env/bin/activate
(env) andrew@ubuntuvm:~/MyProject$ pip install pybuilder
</code></pre>
<p>We can start a blank PyBuilder project with</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ pyb --start-project
</code></pre>
<p>You can hit <code>Enter</code> / <code>Return</code> to accept all of the defaults (these can be changed if you like, but for simplicity's sake, we'll use the defaults here). Note that we don't have to type out the verbose <code>pybuilder</code>, but just <code>pyb</code>. You should now have a <code>MyProject</code> directory that looks like</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ ls
build.py  docs  env  setup.py  src
</code></pre>
<p>...where <code>docs</code>, <code>env</code>, and <code>src</code> are all directories. Your <code>src</code> directory should look like:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ tree src/
src/
|-- main
|   |-- python
|   `-- scripts
`-- unittest
    `-- python

5 directories, 0 files
</code></pre>
<p>The next thing to do is to add some source code to <code>src/main/python</code>, some scripts to <code>/src/main/scripts</code> and some unit tests to <code>/src/unittest/python</code>. To make things easy on myself, I like to make softlinks within environments like this:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ ln -s src/main/python/ source
(env) andrew@ubuntuvm:~/MyProject$ ln -s src/main/scripts/ script
(env) andrew@ubuntuvm:~/MyProject$ ln -s src/unittest/python test
(env) andrew@ubuntuvm:~/MyProject$ ls
build.py  docs  env  script  setup.py  source  src  test
</code></pre>
<p>Now I don't need to remember if the directory was <code>src/main/script</code> or <code>src/python/scripts</code> or if the unit tests are in <code>src/unittests</code> or <code>src/python/main/unittest</code> or whatever. Everything is in the main directory and everything is singular (ie. <code>test</code> instead of <code>tests</code>).</p>
<h2>Managing a PyBuilder Project</h2>
<p>PyBuilder, like many other project management frameworks, is based on the idea of a "build lifecycle", where there are common tasks you'll want to run over and over, like "compile", "run", "document", etc. As an interpreted language, Python doesn't have a "compile" stage in its build lifecycle, but it has most of the main ones. PyBuilder defines <a href="https://gist.github.com/miebach/9752025">lots of different lifecycle stages</a>, but the most common ones are</p>
<ul>
<li><code>pyb publish</code> and</li>
<li><code>pyb clean</code></li>
</ul>
<p><em>"What about unit tests?"</em> you cry. <em>"WHAT ABOUT CODE COVERAGE?"</em> you scream in anguish. They're covered under <code>publish</code>, don't worry. Before we add any code to the project, let's take a look at <code>build.py</code>:</p>
<pre><code class="hljs language-python">from pybuilder.core import use_plugin, init

use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.install_dependencies")
use_plugin("python.flake8")
use_plugin("python.coverage")
use_plugin("python.distutils")


name = "MyProject"
default_task = "publish"


@init
def set_properties(project):
    pass
</code></pre>
<p><code>build.py</code> defines the plugins, settings, tasks, and so on that will be used throughout the build lifecycle. Let's add a few things here, like a description, an author, and some project properties (it's difficult to find a list of these online, but <a href="https://github.com/pybuilder/pybuilder/blob/master/src/main/python/pybuilder/core.py">if you search for <code>self.home_page</code> in PyBuilder's <code>core.py</code> code</a>, that list is pretty close to what's available to use):</p>
<pre><code class="hljs language-python">from pybuilder.core import use_plugin, init, Author

use_plugin("python.core")
use_plugin("python.unittest")
use_plugin("python.install_dependencies")
use_plugin("python.flake8")
use_plugin("python.coverage")
use_plugin("python.distutils")

name    = "MyProject"
version = "1.0"

summary = "Example PyBuilder / Git project"
url     = "https://github.com/awwsmm/PybGit"

description = """An example PyBuilder / Git project for project management
and file version control. See blog post at http://bit.ly/2QY65wO for a
more through explanation."""

authors      = [Author("Andrew Watson", "andrew.watson@nibrt.ie")]
license      = "None"
default_task = "publish"

@init
def initialize(project):
    project.build_depends_on("mockito")

@init
def set_properties(project):
    pass
</code></pre>
<p>Note that we had to add <code>Author</code> to the import list to add a list of authors to the project. Everything else is fairly self explanatory; note in particular that the GitHub URL doesn't need to match the name of the directory in which we've saved the project. We also added a dependency on <code>mockito</code>, which we'll use for some unit testing. What about <code>default_task</code>, though? That defines what PyBuilder should do when we just enter <code>pyb</code> at the command prompt, with no additional arguments. Let's try that now:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ pyb
PyBuilder version 0.11.17
Build started at 2018-09-25 12:45:38
------------------------------------------------------------
[INFO]  Building MyProject version 1.0
[INFO]  Executing build in /home/andrew/MyProject
[INFO]  Going to execute task publish
[INFO]  Running unit tests
[INFO]  Executing unit tests from Python modules in /home/andrew/MyProject/src/unittest/python
[WARN]  No unit tests executed.
[INFO]  All unit tests passed.
[INFO]  Building distribution in /home/andrew/MyProject/target/dist/MyProject-1.0
[INFO]  Copying scripts to /home/andrew/MyProject/target/dist/MyProject- 1.0/scripts
[INFO]  Writing setup.py as /home/andrew/MyProject/target/dist/MyProject-1.0/setup.py
[INFO]  Collecting coverage information
[WARN]  coverage_branch_threshold_warn is 0 and branch coverage will not be checked
[WARN]  coverage_branch_partial_threshold_warn is 0 and partial branch coverage will not be checked
[INFO]  Running unit tests
[INFO]  Executing unit tests from Python modules in /home/andrew/MyProject/src/unittest/python
[WARN]  No unit tests executed.
[INFO]  All unit tests passed.
Coverage.py warning: No data was collected. (no-data-collected)
[INFO]  Overall coverage is 100%
[INFO]  Overall coverage branch coverage is 100%
[INFO]  Overall coverage partial branch coverage is 100%
------------------------------------------------------------
BUILD FAILED - No data to report.
------------------------------------------------------------
Build finished at 2018-09-25 12:45:38
Build took 0 seconds (619 ms)
</code></pre>
<p>We got the error message <code>BUILD FAILED - No data to report.</code> because we don't yet have any files in the project. Let's add a few.</p>
<p>Add the following text to <code>/src/main/python/example_hello.py</code> (aka. <code>source/example_hello.py</code>):</p>
<pre><code class="hljs language-python">import sys

"""Prints \"Hello World!\" to the given output stream."""
def hello_world(out):
    """
    Prints \"Hello World!\".
    >>> import sys
    >>> hello_world(sys.stdout)
    Hello World!\n
    """
    out.write("Hello World!\n")

"""

Below:

 > Required in order to run the documentation checker on this code.

 > The comment
     pragma: no cover
   means that this block of code will not be checked for unit test
   coverage by the `coverage` module.

"""

if __name__ == "__main__": # pragma: no cover
    import doctest
    doctest.testmod()
</code></pre>
<p>Next, we need to add some unit tests for this source code. Add the following text to <code>test/example_hello_tests.py</code>:</p>
<pre><code class="hljs language-python">from mockito import mock, verify
import unittest

from example_hello import hello_world

class HelloWorldTest(unittest.TestCase):

    def test_correct_message(self):
        out = mock()
        hello_world(out)
        verify(out).write("Hello World!\n")
</code></pre>
<p>By convention (and required by PyBuilder), the unit tests for <code>source/abcd.py</code> will be in <code>test/abcd_tests.py</code>. Note that, above, we're using both <a href="https://docs.python.org/3/library/unittest.html">the standard Python unit test package <code>unittest</code></a> as well as <a href="https://pypi.org/project/mockito/">the mock object package <code>mockito</code></a>. Mockito isn't strictly necessary for unit testing, but it can make things faster and easier.</p>
<p>We're also importing the method <code>hello_world</code> from the file <code>example_hello</code> (without the <code>.py</code>). PyBuilder knows where to find these files and everything "just works". Let's try building our package again with <code>pyb</code>:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ pyb
PyBuilder version 0.11.17
Build started at 2018-09-25 14:22:11
------------------------------------------------------------
[INFO]  Building MyProject version 1.0
[INFO]  Executing build in /home/andrew/MyProject
[INFO]  Going to execute task publish
[INFO]  Running unit tests
[INFO]  Executing unit tests from Python modules in /home/andrew/MyProject/src/unittest/python
[INFO]  Executed 1 unit tests
[ERROR] Test has error: unittest.loader._FailedTest.example_hello_tests
------------------------------------------------------------
BUILD FAILED - There were 1 error(s) and 0 failure(s) in unit tests
------------------------------------------------------------
Build finished at 2018-09-25 14:22:11
Build took 0 seconds (318 ms)
</code></pre>
<p>What happened? Let's run <code>pyb</code> again with the <code>-v</code> (verbose) flag:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ pyb -v
PyBuilder version 0.11.17
Build started at 2018-09-25 14:22:21
------------------------------------------------------------
[INFO]  Building MyProject version 1.0
[INFO]  Executing build in /home/andrew/MyProject
[INFO]  Going to execute task publish
[INFO]  Running unit tests
[INFO]  Executing unit tests from Python modules in /home/andrew/MyProject/src/unittest/python
[INFO]  Executed 1 unit tests
[ERROR] Test has error: unittest.loader._FailedTest.example_hello_tests
ImportError: Failed to import test module: example_hello_tests
Traceback (most recent call last):
  File "/usr/lib/python3.5/unittest/loader.py", line 153, in loadTestsFromName
    module = __import__(module_name)
  File "/home/andrew/MyProject/src/unittest/python/example_hello_tests.py", line 1, in &#x3C;module>
    from mockito import mock, verify
ImportError: No module named 'mockito'


------------------------------------------------------------
BUILD FAILED - There were 1 error(s) and 0 failure(s) in unit tests
------------------------------------------------------------
Build finished at 2018-09-25 14:22:21
Build took 0 seconds (312 ms)
</code></pre>
<p>Oh! It's because we forgot to install the dependencies that we included in <code>build.py</code> (namely, Mockito). Let's do that now:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ pyb install_dependencies
PyBuilder version 0.11.17
Build started at 2018-09-25 14:25:13
------------------------------------------------------------
[INFO]  Building MyProject version 1.0
[INFO]  Executing build in /home/andrew/MyProject
[INFO]  Going to execute task install_dependencies
[INFO]  Installing all dependencies
[INFO]  Processing batch dependency 'mockito'
------------------------------------------------------------
BUILD SUCCESSFUL
------------------------------------------------------------
Build Summary
             Project: MyProject
             Version: 1.0
      Base directory: /home/andrew/MyProject
        Environments:
               Tasks: install_dependencies [3247 ms]
Build finished at 2018-09-25 14:25:16
Build took 3 seconds (3259 ms)
</code></pre>
<p>Yes, it really is that easy. We can run <code>pyb</code> again now, and we get a <code>BUILD SUCCESSFUL</code> at the end:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ pyb
PyBuilder version 0.11.17
Build started at 2018-09-25 14:25:19
------------------------------------------------------------
[INFO]  Building MyProject version 1.0
[INFO]  Executing build in /home/andrew/MyProject
[INFO]  Going to execute task publish
[INFO]  Running unit tests
[INFO]  Executing unit tests from Python modules in /home/andrew/MyProject/src/unittest/python
[INFO]  Executed 1 unit tests
[INFO]  All unit tests passed.
[INFO]  Building distribution in /home/andrew/MyProject/target/dist/MyProject-1.0
[INFO]  Copying scripts to /home/andrew/MyProject/target/dist/MyProject-1.0/scripts
[INFO]  Writing setup.py as /home/andrew/MyProject/target/dist/MyProject-1.0/setup.py
[INFO]  Collecting coverage information
[WARN]  coverage_branch_threshold_warn is 0 and branch coverage will not be checked
[WARN]  coverage_branch_partial_threshold_warn is 0 and partial branch coverage will not be checked
[INFO]  Running unit tests
[INFO]  Executing unit tests from Python modules in /home/andrew/MyProject/src/unittest/python
[INFO]  Executed 1 unit tests
[INFO]  All unit tests passed.
[INFO]  Overall coverage is 100%
[INFO]  Overall coverage branch coverage is 100%
[INFO]  Overall coverage partial branch coverage is 100%
[INFO]  Building binary distribution in /home/andrew/MyProject/target/dist/MyProject-1.0
------------------------------------------------------------
BUILD SUCCESSFUL
------------------------------------------------------------
Build Summary
             Project: MyProject
             Version: 1.0
      Base directory: /home/andrew/MyProject
        Environments:
               Tasks: prepare [248 ms] compile_sources [0 ms] run_unit_tests [40 ms] package [3 ms] run_integration_tests [0 ms] verify [401 ms] publish [516 ms]
Build finished at 2018-09-25 14:25:20
Build took 1 seconds (1222 ms)
</code></pre>
<p>Don't forget to always run <code>pyb install_dependencies</code> after you add any new dependencies to the <code>build.py</code> file. Note that PyBuilder ran our unit test that we defined in <code>example_hello_tests.py</code>. As long as you place the tests in the correct directory, PyBuilder knows where to find them and what to do with them. Let's add another, slightly more complicated, example. Create a new file called <code>source/example_primes.py</code> and add the following text to it:</p>
<pre><code class="hljs language-python">import math
import itertools

"""Returns a list of N primes, beginning with [2, 3, 5...]."""
def first_N_primes(N):
    """
    Returns a list of N primes, beginning with [2, 3, 5...]. Returns an empty
    list if the user supplies a non-positive number. Floating point numbers
    are rounded up.
    >>> first_N_primes(0)
    []
    >>> first_N_primes(3.14)
    [2, 3, 5, 7]
    >>> first_N_primes(-42)
    []
    >>> first_N_primes(10)
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
    """
    if (N &#x3C;= 0):
        return []

    primes = [2]
    prime  = (x for x in itertools.count(2) if not any ([x%y==0 for y in range(2, int(math.ceil(math.sqrt(x)))+1)]))

    for n in range(1, int(math.ceil(N))):
        primes.append(next(prime))

    return primes

if __name__ == "__main__": # pragma: no cover
    import doctest
    doctest.testmod()
</code></pre>
<p>Note that we've again added this "doctest" block at the bottom of this bit of source code... why? It allows us to verify that the documentation we've written (example usage, beginning with <code>>>></code>) actually works as advertised:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ python3 source/example_primes.py -v
Trying:
    first_N_primes(0)
Expecting:
    []
ok
Trying:
    first_N_primes(3.14)
Expecting:
    [2, 3, 5, 7]
ok
Trying:
    first_N_primes(-42)
Expecting:
    []
ok
Trying:
    first_N_primes(10)
Expecting:
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
ok
1 items had no tests:
    __main__
1 items passed all tests:
   4 tests in __main__.first_N_primes
4 tests in 2 items.
4 passed and 0 failed.
Test passed.
</code></pre>
<p>I don't know about you, but I think that's pretty cool. <code>doctest</code> verifies that our documentation examples actually produce the output that we say they should. If you only want to view the documentation, you can do that with:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ python3 -i source/example_primes.py
>>> help(first_N_primes)
</code></pre>
<p>...or just</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ pydoc ./source/example_primes.py
</code></pre>
<p>Note that you can also get nicely-formatted HTML help by adding the <code>-w</code> flag above. Let's add another set of unit tests for <code>example_primes</code>. In <code>test/example_primes_tests.py</code>, add the following lines of code:</p>
<pre><code class="hljs language-python">import unittest

from example_primes import first_N_primes

class FirstNPrimesTest(unittest.TestCase):

    """ test negative float input """
    def test_negFloatInput(self):
        self.assertEqual(first_N_primes(-14.3), [])

    """ test positive integer input """
    def test_posIntInput(self):
        self.assertEqual(first_N_primes(6), [2, 3, 5, 7, 11, 13])
</code></pre>
<p>Running <code>pyb</code> again verifies that we have 3 unit tests (all of which passed) and that we have 100% code coverage! Success!</p>
<h2>Python Scripts in PyBuilder</h2>
<p>One more thing worth touching on for this intro to PyBuilder is the idea of <em>scripts</em>. A good way to keep code neat is to keep method and class definitions in <code>source/</code> and runnable scripts which use those methods and classes in <code>script/</code>. Let's write a short script that uses the single method defined in <code>source/example_primes.py</code>. Create a file called <code>script/example_primes_script.py</code> and add the following code to it:</p>
<pre><code class="hljs language-python">#!/usr/bin/env python
import sys

from example_primes import first_N_primes

N = 10
print("The first",N,"primes are:")

for n in first_N_primes(N):
    print(n)
print()
</code></pre>
<p>We then re-publish the code with <code>pyb</code>, and we can install the package locally (within the virtual environment) with the command:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ pip install target/diest/MyProject-1.0/dist/MyProject-1.0.tar.gz
</code></pre>
<p>This makes all of the scripts in the project available for us to use, right on the command line. Simply write:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ example_primes_script.py
The first 10 primes are:
2
3
5
7
11
13
17
19
23
29
</code></pre>
<p>Ta da! PyBuilder, again, knows where the scripts are and makes them available to use. If you change any code, make sure you re-publish with <code>pyb</code> and reinstall using the <code>pip install</code> command above. That will make your code available to use freely within the virtual environment.</p>
<h1>Managing Things with Git</h1>
<p>As I said earlier, this doesn't attempt to be an introduction to Git by any means, but there are a few commands here that we can review, which will help us to maintain this project. First, let's see what's changed since we initialized everything with <code>git init</code> way back at the beginning of this tutorial:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ git status
On branch master

Initial commit

Untracked files:
  (use "git add &#x3C;file>..." to include in what will be committed)

        .coverage
        __pycache__/
        build.py
        env/
        script
        setup.py
        source
        src/
        target/
        test

nothing added to commit but untracked files present (use "git add" to track)
</code></pre>
<p>...okay, everything. A good <code>.gitignore</code> file is probably in order, since we don't want our repo to be clogged with the hundreds of files in our virtual environment directory, <code>env</code>. Probably, we only want to commit our source code, unit tests, scripts, and information about our build environment (also maybe our soft links). Let's <code>gitignore</code> everything else. Create a file called <code>.gitignore</code> and add the following lines to it:</p>
<pre><code>.coverage
__pycache__
env
target
</code></pre>
<p>If directories are added to <code>.gitignore</code>, that directory and everything in it is ignored when we run <code>git status</code>. Let's see what we have left:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ git status

On branch master

Initial commit

Untracked files:
  (use "git add &#x3C;file>..." to include in what will be committed)

        .gitignore
        build.py
        script
        setup.py
        source
        src/
        test

nothing added to commit but untracked files present (use "git add" to track)
</code></pre>
<p>Okay! Just code, soft links, and some configuration files. Let's add all of this to our initial commit:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ git add .gitignore

(env) andrew@ubuntuvm:~/MyProject$ git add *
</code></pre>
<p>Note that here you might get a warning about some files being ignored -- that's fine, we purposefully put those files in <code>.gitignore</code> because we wanted to ignore them. Let's commit these files to our local git repo:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ git commit -am "initial commit"
</code></pre>
<p>We've committed all (<code>-a</code>) the files we had staged and added a message (<code>-m</code>) which indicates that this is our first commit to this repo. Next, if you have a GitHub (or other similar account like BitBucket, etc.), you can easily create a remote repo to host your code.</p>
<h2>Creating a GitHub Repository</h2>
<p>To create a remote repository hosted on GitHub, simply go to your profile page:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/hlyvcrh4ktr88bej7qad.PNG" alt=""></p>
<p>Click the "Repositories" link at the top:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/ekcwyrapxyxjkb4n1cmy.PNG" alt=""></p>
<p>Then click the green "New" button over on the right:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/bxotj4in6qd8qjmjjcfj.PNG" alt=""></p>
<p>Name your repo, give it a description...</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/rcjmfuenl7sdmbgaz0qi.PNG" alt=""></p>
<p>...and follow the instructions! We want to "push an existing repository from the command line", because we've already got our directory structure all figured out and added our files, etc. Make sure you've <a href="https://jdblischak.github.io/2014-09-18-chicago/novice/git/05-sshkeys.html">added your ssh key to GitHub</a> so that you can push to your remote repo, and run the following two commands (as the instructions tell you to do):</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ git remote add origin git@github.com:awwsmm/PybGit.git

(env) andrew@ubuntuvm:~/MyProject$ git push -u origin master
</code></pre>
<p>That's it! You now have a Git/PyBuilder project with version control, unit tests, documentation, and a nice, organized directory structure:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/usojnbbre9nv17zpkrsr.PNG" alt=""></p>
<h2>Oh Wait, One More Thing</h2>
<p>Say we forgot to add a file to our remote repo, or we've changed something and we want to update it. No worries. Now that we have our remote repo up and running, it's pretty easy. Let's make a new file called <code>script/example_hello_script.py</code> and add the following code to it:</p>
<pre><code class="hljs language-python">#!/usr/bin/env python
import sys

"""
Writes "Hello from a script!" to stdout.
"""

sys.stdout.write("Hello from a script!\n")
</code></pre>
<p>Nothing special here. But we need to go through a few steps. First, re-publish the project with <code>pyb publish</code> (or just <code>pyb</code>, as we've been doing, since we have the <code>default_task</code> set to "publish" in our <code>build.py</code> file):</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ pyb
</code></pre>
<p>Then, re-install the package in our virtual environment:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ pip install target/dist/MyProject-1.0/dist/MyProject-1.0.tar.gz
</code></pre>
<p>Verify that our new script works before we commit it to our local repo:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ example_hello_script.py
Hello from a script!
</code></pre>
<p>It does, cool. If we run <code>git status</code>, we can see that the repository has changed -- we have a new untracked file.</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Untracked files:
  (use "git add &#x3C;file>..." to include in what will be committed)

        src/main/scripts/example_hello_script.py

nothing added to commit but untracked files present (use "git add" to track)
</code></pre>
<p>Add it to Git (make sure it's tracked) with:</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ git add src/main/scripts/example_hello_script.py
</code></pre>
<p>(Note that we can't use our soft links here to make this command shorter.) Commit our changes to the local repository with</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ git commit -am "new hello script"
</code></pre>
<p>...and push them to the remote one with</p>
<pre><code class="hljs language-shell">(env) andrew@ubuntuvm:~/MyProject$ git push
</code></pre>
<p>We can see that this commit has been pushed to the remote repo (there are now two commits instead of one):</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/9nlaep3840vyy4pnimxh.PNG" alt=""></p>
<h1>Conclusion</h1>
<p>And that's it. Hopefully this guide has helped you to avoid some of the missteps that I made in getting my PyBuilder/Git project up and running.</p>
<p>All the code from this post is available at <a href="https://github.com/awwsmm/PybGit">awwsmm.com/PybGit</a>.</p></div>]]></content:encoded>
            <author>aww@awwsmm.com (Andrew William Watson)</author>
        </item>
    </channel>
</rss>