<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Eduardo Rodrigues on Medium]]></title>
        <description><![CDATA[Stories by Eduardo Rodrigues on Medium]]></description>
        <link>https://medium.com/@EduardoRodriguesF?source=rss-3c232a2263b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c3ImQJQBakbTMA_FYLeogg.png</url>
            <title>Stories by Eduardo Rodrigues on Medium</title>
            <link>https://medium.com/@EduardoRodriguesF?source=rss-3c232a2263b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:26:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@EduardoRodriguesF/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Vim: start using QuickFix lists]]></title>
            <link>https://medium.com/@EduardoRodriguesF/vim-start-using-quickfix-lists-e43a7a29ba52?source=rss-3c232a2263b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e43a7a29ba52</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vim]]></category>
            <dc:creator><![CDATA[Eduardo Rodrigues]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 13:40:33 GMT</pubDate>
            <atom:updated>2024-04-27T13:40:33.517Z</atom:updated>
            <content:encoded><![CDATA[<p>Vim has 1001 ways to get things done, but one of my favorites that I’ve just recently engaged with is the quickfix feature. Today, we’ll learn how quickfix help us traverse and modify large lists of positions in different files with ease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-ubfBrYhxE2mC4AdJNjDA.png" /></figure><h3>What is QuickFix?</h3><p>To put it simple, the quickfix is a list of positions in files. According to the documentation:</p><blockquote>The idea is to save the error messages from the compiler in a file and use Vim<br>to jump to the errors one by one.</blockquote><p>Although the idea was born from a C compiler, you can use quickfix for virtually any kind of traceable pattern, like errors, keywords, and references.</p><h3>Getting started with QuickFix</h3><p>Some Vim features will natively integrate quickfix. The first example everyone talks about when introducing it is vimgrep command, which is Vim’s built-in Grep implementation.</p><p>Just like Grep, it can be used to find patterns in the specified files. Vimgrep is no different, except that the results will automatically fill the quickfix list for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFnlWD8soxQlgbamdokWsg.gif" /></figure><p>Here, I searched for “loader” in all files in sections directory. I then used :copen to open the quickfix list, where I am able to navigate through the list as if it was a simple file, and select the entry I want to go to.</p><p>There are much more we can do with it. In fact, you don’t even need to open the quickfix list to traverse through the items, since there are proper commands for going to the next and previous items.</p><h4>Basic commands</h4><p>These are the essentials commands to use quickfix lists. We’ll use then in the remaining of this article.</p><ul><li>copen — open quickfix list in a separate window</li><li>cclose — close quickfix list</li><li>cn[ext] — go to next item in the list</li><li>cp[rev] — go to previous item in the list</li></ul><h4>Simple yet powerful remaps</h4><p>No one wants to :cnext and :cprev all the time. Remapping is there to help us out, so let’s make good use of it. I like to traverse my quickfix through C-j and C-k — resembling the foundation of our beloved Vim motions’ up and down movements.</p><pre>nnoremap &lt;C-j&gt; :cnext&lt;cr&gt;<br>nnoremap &lt;C-k&gt; :cprev&lt;cr&gt;</pre><h4>QuickFix DO</h4><p>A powerful way to take advantage of quickfix is the :cdo command — the <em>QuickFix DO</em>. With that, we can execute commands that runs for each position mapped in the list. A simple example is a substitution:</p><pre>:cdo s/bug/fixed/</pre><p>But the magic is when you put that with the :norm command, which allow us to do motions within each position.</p><p>Let’s say that I have a few JavaScript functions which are declared with the arrow syntax. For those who do not program in JS, it is basically transforming this:</p><pre>const loader = (param: unknown) =&gt; { /* function body */ }</pre><p>Into this:</p><pre>function loader(param: unknown) { /* function body */ }</pre><p>Assuming I already have my quickfix filled from Vimgrep, I <em>could</em> do something like</p><pre>:cdo norm _:s/const/function&lt;cr&gt;f=hdt(</pre><p>…and so on. To make it easier, we can record a macro doing it for one of the entries first:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezUR4KvC7MXcFI6muSRjAw.gif" /></figure><p>If we take a look at the j register now, we have the following macro:</p><pre>_:s/const/function^Mf=&lt;80&gt;&lt;fd&gt;ahdt(&lt;80&gt;&lt;fd&gt;a%ldt{&lt;80&gt;&lt;fd&gt;ai ^[:&lt;80&gt;kb</pre><p>Sure there are a couple of unnecessary moves, but it does the job. We can simply :cdo it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZTSX7qrt75CjyCHrkUINA.gif" /></figure><h3>Other Practical usage</h3><h4>LSP definitions</h4><p>All LSP’s have a goto-reference type of action. The beauty is that they will fill the quickfix list with those references, making it smooth to, for example, jump to all locations where an Image component is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwKaXQl_Vsr8CMLtViN2Cg.gif" /></figure><h4>Telescope (NeoVim)</h4><p>At this point, Telescope is a must-have when daily-driving NeoVim. The basic features of file search and keyword search are fenomenal by their own, but a pain if not used properly.</p><p>By default, C-q is mapped to Telescope action send_selection_to_qflist which do what it says: it sends the selected entries to the quickfix list!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*sg3y-3Q_tcdWmqDMJRn7EQ.gif" /></figure><p>Traversing files or keywords from Telescope has never been so easy.</p><h3>Conclusion</h3><p>We’ve just scratched the surface about quickfix lists. We haven’t even talked about scripts for generating quickfixes. But with the little I’ve shown, I was able to greatly improve my Vim game!</p><p>I hope you find use for it in your workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e43a7a29ba52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(C++) How to ruin performance and memory efficiency]]></title>
            <link>https://towardsdev.com/c-how-to-ruin-performance-and-memory-efficiency-4490590fe54?source=rss-3c232a2263b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4490590fe54</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[advent-of-code]]></category>
            <dc:creator><![CDATA[Eduardo Rodrigues]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 14:43:31 GMT</pubDate>
            <atom:updated>2023-09-19T15:03:22.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOoyTJ62KROS_eIXOVxp_Q.png" /></figure><p>For the past month I’ve been taking my free time to learn C++. The way I am approaching the language is picking <a href="https://adventofcode.com/2022">Advent of Code 2022</a> challenges and solve it in the language.</p><p>I’m writing this article because I’ve been through a huge performance issue with my application, and it might help some of the readers out there to overcome it.</p><h3>The challenge</h3><p>The <a href="https://adventofcode.com/2022/day/8">Day 8 (part 1)</a> challenge consists in a plain text that represents a grid. In that grid, each digit is the height of a tree in that location.</p><pre>30373<br>25512<br>65332<br>33549<br>35390</pre><p>We need to count the trees visible from outside the grid. According to the prompt:</p><blockquote>A tree is visible if all of the other trees between it and an edge of the grid are shorter than it. Only consider trees in the same row or column; that is, only look up, down, left, or right from any given tree.</blockquote><blockquote>All of the trees around the edge of the grid are visible — since they are already on the edge, there are no trees to block the view.</blockquote><p>We are given a 99x99 grid to work with, that gives us 9.801 total positions to deal with.</p><h4>The initial solution</h4><p>Although I did solve the challenge, it took <strong>over 3 minutes</strong> for the program to complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CExjXNZwpBzh0wSRTMQaew.png" /><figcaption>Benchmark done with hyperfine</figcaption></figure><h4>Why is it so slow?</h4><p>To understand the problem, let’s first take a tour to the grid structure. All logic involving the grid itself is declared in a grid.h file:</p><pre>#include &lt;fstream&gt;<br>#include &lt;memory&gt;<br>#include &lt;optional&gt;<br>#include &lt;string&gt;<br>#include &lt;utility&gt;<br>#include &lt;vector&gt;<br><br>class Grid;<br><br>struct CellNeighbors;<br><br>enum Direction {<br> Top,<br> Right,<br> Bottom,<br> Left<br>};<br><br>struct Pos {<br> size_t x;<br> size_t y;<br>};<br><br>struct GridCell {<br> std::shared_ptr&lt;Grid&gt; parent;<br> unsigned int height;<br> Pos pos;<br><br> CellNeighbors direct_neighbors() const;<br> std::vector&lt;std::optional&lt;GridCell&gt;&gt; direct_neighbors_list() const;<br><br> std::vector&lt;std::vector&lt;GridCell&gt;&gt; adjacent_neighbors() const;<br>};<br><br>struct CellNeighbors {<br> std::optional&lt;GridCell&gt; top;<br> std::optional&lt;GridCell&gt; right;<br> std::optional&lt;GridCell&gt; bottom;<br> std::optional&lt;GridCell&gt; left;<br>};<br><br>class Grid {<br>public:<br> Grid(std::ifstream &amp;file);<br><br> std::vector&lt;int&gt; neighbors() const;<br> std::optional&lt;GridCell&gt; at(Pos pos) const;<br> std::optional&lt;GridCell&gt; at(size_t x, size_t y) const;<br><br> std::pair&lt;size_t, size_t&gt; sizes() const;<br><br>private:<br> std::vector&lt;std::vector&lt;int&gt;&gt; data;<br>};</pre><p>I won’t go in details about every aspect for now, but the important thing to notice is that the grid data is right here:</p><pre>std::vector&lt;std::vector&lt;int&gt;&gt; data;</pre><p>data is a vector of rows, where each element is a column, and every column is a vector of the tree heights represented by an int.</p><p>This is the function that calculates the final result:</p><pre>size_t total_visible_trees(const Grid &amp;map) {<br> size_t result = 0;<br> auto [x_size, y_size] = map.sizes();<br><br> for (size_t x = 0; x &lt; x_size; x++) {<br>  for (size_t y = 0; y &lt; y_size; y++) {<br>   auto cell = map.at(x, y);<br>   auto direct_neighbors = cell-&gt;direct_neighbors_list();<br><br>   bool is_surrounded = std::all_of(direct_neighbors.begin(), direct_neighbors.end(), [](std::optional&lt;GridCell&gt; cell) {<br>    return cell.has_value();<br>   });<br><br>   if (!is_surrounded) {<br>    result++;<br>    continue;<br>   }<br><br>   auto adjacents = cell-&gt;adjacent_neighbors();<br><br>   for (const auto &amp;neighbors : adjacents) {<br>    bool is_visible = std::all_of(neighbors.begin(), neighbors.end(), [cell](GridCell neighbor) {<br>     return neighbor.height &lt; cell-&gt;height;<br>    });<br><br>    if (is_visible) {<br>     result++;<br>     goto cnt;<br>    }<br>   }<br><br>   cnt:;<br>  }<br> }<br><br> return result;<br>}</pre><p>As we saw earlier, we need 9.801 to check each position, but for each position we also need to check all directions. There are already some continues in place to avoid unnecessary iterations, like trees on the edges.</p><pre>   bool is_surrounded = std::all_of(direct_neighbors.begin(), direct_neighbors.end(), [](std::optional&lt;GridCell&gt; cell) {<br>    return cell.has_value();<br>   });<br><br>   if (!is_surrounded) {<br>    result++;<br>    continue;<br>   }</pre><p>GridCell::direct_neighbors_list will use Grid::at method to check top, right, bottom and left sides.</p><p>If it is surrounded, we don’t need to check for adjacent neighbors blocking the view. However, any interior tree needs to check all four directions until some (if any) makes the tree visible.</p><p>Also, if we find one direction that makes this tree visible, there is no need for us to keep checking other sides. For that, GridCell:adjacent_neighbors is used to check all sides as the previous method did, but it returns a list for each direction until it reaches the end.</p><pre>   for (const auto &amp;neighbors : adjacents) {<br>    bool is_visible = std::all_of(neighbors.begin(), neighbors.end(), [cell](GridCell neighbor) {<br>     return neighbor.height &lt; cell-&gt;height;<br>    });<br><br>    if (is_visible) {<br>     result++;<br>     goto cnt;<br>    }<br>   }<br><br>   cnt:;</pre><p>To show how all this would function,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rh6c0OLwUQ8dbczgTx1v8A.png" /><figcaption>Sample 12x8 grid</figcaption></figure><p>this sample grid has 96 positions — much less than our 9.801. In this diagram, the arrows indicate how far iterations for each directions went, while the red dot is each neighbor that was checked to see if they are smaller than our tree (5).</p><p>For our real grid, we are talking about <strong>35.836 </strong>iterations when checking visibility — average of 3.65 inner iterations for each — until we can determine if a given tree is visible.</p><p>Now let’s be honest. If you’ve been to programming for a while, you can see that this is not that much iterations for a computer. This solution is underperforming by a lot more than it should.</p><h3>Finding the root</h3><p>One thing you might have noticed is that for, for every given position, we resolve a grid cell by using Grid::at(size_t x, size_t y) method.</p><p>Previously, I mentioned that our program deals with almost 36k iterations. However, Grid::adjacent_neighbors aims to be modular, and thus it does not care whether some direction makes the tree visible or not — it always resolves the full direction range.</p><pre>std::vector&lt;std::vector&lt;GridCell&gt;&gt; GridCell::adjacent_neighbors() const {<br> std::vector&lt;std::vector&lt;GridCell&gt;&gt; result(4);<br><br> for (size_t ny = this-&gt;pos.y - 1; ny &gt;= 0; ny--) {<br>  auto node = this-&gt;parent-&gt;at(this-&gt;pos.x, ny);<br>  if (!node.has_value()) {<br>   break;<br>  }<br><br>  result[Direction::Top].push_back(node.value());<br> }<br><br> for (size_t nx = this-&gt;pos.x + 1; nx &lt; this-&gt;parent-&gt;sizes().first; nx++) {<br>  auto node = this-&gt;parent-&gt;at(nx, this-&gt;pos.y);<br>  if (!node.has_value()) {<br>   break;<br>  }<br><br>  result[Direction::Right].push_back(node.value());<br> }<br><br> for (size_t ny = this-&gt;pos.y + 1; ny &lt; this-&gt;parent-&gt;sizes().second; ny++) {<br>  auto node = this-&gt;parent-&gt;at(this-&gt;pos.x, ny);<br>  if (!node.has_value()) {<br>   break;<br>  }<br><br>  result[Direction::Bottom].push_back(node.value());<br> }<br><br> for (size_t nx = this-&gt;pos.x - 1; nx &gt;= 0; nx--) {<br>  auto node = this-&gt;parent-&gt;at(nx, this-&gt;pos.y);<br>  if (!node.has_value()) {<br>   break;<br>  }<br><br>  result[Direction::Left].push_back(node.value());<br> }<br><br> return result;<br>}</pre><p>Doing some quick calculation, the way we structure the code, it first resolves all adjacent neighbors and then iterates over them to see if some direction is visible. That is, for a tree in the middle it has to create <strong>new</strong> GridCells for almost 50 trees top, right, down, and left — roughly 200 initializations.</p><p>This is the worst case scenario though, but even if we consider a gentle average of 1/3 of that value, we are still talking about something of more than <strong>645.000 </strong>iterations + 36k to check visibility: total of 676k.</p><p>As we can see in the snippet above, we also use Grid::at here. What it does it simply creating a GridCell based on these coordinates as below:</p><pre><br>std::optional&lt;GridCell&gt; Grid::at(size_t x, size_t y) const {<br> return this-&gt;at(Pos { x, y });<br>}<br><br>std::optional&lt;GridCell&gt; Grid::at(Pos pos) const {<br> if (pos.y &gt; this-&gt;data.size() - 1 || pos.x &gt; this-&gt;data[pos.y].size()) {<br>  return std::nullopt;<br> }<br><br> GridCell cell;<br><br> cell.parent = std::make_shared&lt;Grid&gt;(*this);<br> cell.pos = pos;<br> cell.height = this-&gt;data[pos.y][pos.x];<br><br> return cell;<br>}</pre><p>For beginners — myself included until now — it might not seem a big deal, since GridCell is nothing more than a struct.</p><h3>The true beauty of pointers</h3><p>Although the program takes 190 seconds to complete, the time it takes to generate the entire Grid instance is a short 500ms — that is, reading from the data file and putting all the values in a 2D vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GcfhlKhzmx8D0smd0F7T4Q.png" /></figure><p>So, how much more time would we take if we replace our std::vector&lt;std::vector&lt;int&gt;&gt; for a std::vector&lt;std::vector&lt;GridCell&gt;&gt;? Would it still be that quick?</p><p>Only way to know is by trying. Now our grid constructor will have this body:</p><pre>Grid::Grid(std::ifstream &amp;file) {<br> std::string line;<br><br> size_t y = 0;<br> while (std::getline(file, line)) {<br>  std::vector&lt;std::unique_ptr&lt;GridCell&gt;&gt; row;<br>  std::istringstream ss(line);<br>  char tree;<br><br>  size_t x = 0;<br>  while (ss &gt;&gt; tree) {<br>   auto cell = GridCell(*this);<br><br>   cell.pos = Pos { x, y };<br>   cell.height = tree - &#39;0&#39;; // converted to int<br><br>   row.push_back(std::make_unique&lt;GridCell&gt;(cell));<br>   x++;<br>  }<br><br>  this-&gt;data.push_back(std::move(row));<br>  y++;<br> }<br>}</pre><p>Notice that we actually used a unique pointer instead of the raw value, and we’re covering that soon. But notice that most of the logic that was found in Grid::at is now here.</p><p>Let’s see what our benchmark thinks about it…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jq9WcsN-Qxzs9ZoG_19EZw.png" /></figure><p>Wow, near to no loss comparing for the total runtime it was.</p><p>This is the part I like the most. Instead of creating <strong>new</strong> cells everytime we consult a position, we’re simply returning a pointer to the value at Grid::data matrix.</p><pre>std::optional&lt;GridCell *&gt; Grid::at(size_t x, size_t y) const {<br> if (y &gt;= this-&gt;data.size() || x &gt;= this-&gt;data[y].size()) {<br>  return std::nullopt;<br> }<br><br> return this-&gt;data[y][x].get();<br>}</pre><p>Actually, anywhere that uses GridCells now receives a GridCell* instead! Take a look at how grid.h ended up:</p><pre>#include &lt;fstream&gt;<br>#include &lt;memory&gt;<br>#include &lt;optional&gt;<br>#include &lt;string&gt;<br>#include &lt;utility&gt;<br>#include &lt;vector&gt;<br><br>class Grid;<br><br>struct CellNeighbors;<br><br>enum Direction {<br> Top,<br> Right,<br> Bottom,<br> Left<br>};<br><br>struct Pos {<br> size_t x;<br> size_t y;<br>};<br><br>struct GridCell {<br> Grid &amp;parent;<br> unsigned int height;<br> Pos pos;<br><br> GridCell(Grid &amp;p) : parent(p) {};<br><br> CellNeighbors direct_neighbors() const;<br> std::vector&lt;std::optional&lt;GridCell *&gt;&gt; direct_neighbors_list() const;<br><br> std::vector&lt;std::vector&lt;GridCell *&gt;&gt; adjacent_neighbors() const;<br>};<br><br>struct CellNeighbors {<br> std::optional&lt;GridCell *&gt; top;<br> std::optional&lt;GridCell *&gt; right;<br> std::optional&lt;GridCell *&gt; bottom;<br> std::optional&lt;GridCell *&gt; left;<br>};<br><br>class Grid {<br>public:<br> Grid(std::ifstream &amp;file);<br><br> std::vector&lt;int&gt; neighbors() const;<br> std::optional&lt;GridCell *&gt; at(Pos pos) const;<br> std::optional&lt;GridCell *&gt; at(size_t x, size_t y) const;<br><br> std::pair&lt;size_t, size_t&gt; sizes() const;<br><br>private:<br> std::vector&lt;std::vector&lt;std::unique_ptr&lt;GridCell&gt;&gt;&gt; data;<br>};</pre><h4>Aren’t raw pointers bad or something?</h4><p>That was the first thing I thought when coming to that solution. In C++, raw pointers are bad practices only when we are handling the creation and deletion with new and delete keywords ourselves.</p><p>Since we are using a smart pointer std::unique_ptr, all that is handled under the hood for us. .get() returns a raw pointer that we can freely use without worrying about freeing the memory ourselves.</p><p>For the sake of curiosity, if we use delete on the cell for each loop we go through, look what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Mk4qUE5IGrTFr1FdeGziQ.png" /></figure><p>Doing so is nonsensical anyways since we know that we are going to need the values later, but that doesn’t matter for this explanation. When using unique_ptr::get(), we do receive a raw pointer for the object, but unique_ptr won’t give up ownership of it — thus we cannot manage its memory.</p><p>Whenever this unique pointer goes out of scope (that would be when Grid goes out of scope, since it is a member of it) the memory address will be freed.</p><h3>After all, did it solve?</h3><p>Before writing this article, I thought it’d be necessary to cut down extra iteration cycles. However, the last benchmarks blew my mind:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ti43PGwI8Opih--leyQIqg.png" /></figure><p>And remember, this is the first run only. If we let the file system warm up before, the result is even more impressive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-u9Scs9cKNbUJhojIsp1g.png" /></figure><p>Now this is a real C++ performance!</p><p>If you want to see the entire code solution for this and part 2 of the problem, here is the link to the repository:</p><p><a href="https://github.com/EduardoRodriguesF/advent-of-cpp/tree/main/day-8">advent-of-cpp/day-8 at main · EduardoRodriguesF/advent-of-cpp</a></p><h3>Final thoughts</h3><p>For me, this was the ultimate example of how performance and memory efficiency can be ruined by bad instantiations. It is moments like that that show us the real power of what pointers can do for us — specially smart pointers.</p><p>Is this the best performing code for the challenge possible? Surely not. However, I learned a lot taking it and then spending some extra time improving upon it. I hope this article helps you if you find yourself in a similar situation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4490590fe54" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/c-how-to-ruin-performance-and-memory-efficiency-4490590fe54">(C++) How to ruin performance and memory efficiency</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swim with Vimdiff and You’ll Never Drown in Merge Conflicts Ever Again]]></title>
            <link>https://medium.com/@EduardoRodriguesF/swim-with-vimdiff-and-youll-never-drown-in-merge-conflicts-ever-again-71df98d4a84c?source=rss-3c232a2263b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/71df98d4a84c</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[merge-conflicts]]></category>
            <dc:creator><![CDATA[Eduardo Rodrigues]]></dc:creator>
            <pubDate>Thu, 04 May 2023 09:01:35 GMT</pubDate>
            <atom:updated>2023-05-05T14:08:20.036Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I use Vimdiff to make Merge Conflicts easier</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*0bfko6CmhE08XYO-isS8-Q.png" /><figcaption>Screenshot by me</figcaption></figure><p>Knowing the tools you use changes the way you approach problems. Merge conflicts can already get complicated enough, so we need to stay sharp on our arsenal choice.</p><p>For those who already follow me, it’s probably obvious that I am about to talk more about Vim.</p><p><a href="https://medium.com/@EduardoRodriguesF/the-groundbreaking-vim-experience-88b267dd2f67">The Groundbreaking Vim Experience</a></p><p>Personally, I prefer NeoVim for daily usage. However, I chose to go with Vim for this article.</p><p>Not only that, but I’ll be doing things that way because I want to show you that <strong>no extra configuration is needed.</strong> No plugins, no remaps, just plain Vim. Everything works out-of-the-box this exact way — <em>and works great</em>. So we’re not talking about Fugitive or any game changing implementation, just plain Vim tools.</p><h3>Our Project</h3><p>Any good article has its loyal examples to help further introduce key-points and problems in practice. Let’s get used to ours. I created a simple program in Rust about cats. Don’t worry, you don’t have to know Rust to follow the article, it won’t matter that much.</p><p>We have our lib.rs file where most our logic will be:</p><pre>pub struct Cat {<br>    pub name: String,<br>}<br><br>impl Cat {<br>    pub fn new(name: &amp;str) -&gt; Self {<br>        Self {<br>            name: name.to_string(),<br>        }<br>    }<br><br>    pub fn meow(&amp;`) {<br>        println!(&quot;{}: Meow!&quot;, self.name);<br>    }<br>}</pre><p>Although the actual implementation doesn’t matter: Cat can have a name. It also comes with two methods for creating new cats (new) and a meow method, which will simply print &quot;{name}: Meow!&quot;.</p><p>So far so good. Now the file that makes everything run, the main.rs file:</p><pre>use hello_medium::Cat;<br><br>fn main() {<br>    let chanel = Cat::new(&quot;Chanel&quot;);<br><br>    chanel.meow();<br>}</pre><p>It imports Cat, creates a new one named Chanel and makes it meow.</p><h4>Inspiration</h4><p>This simple 30 lines program is inspired by my cat named Coco Chanel:</p><figure><img alt="My cat lying between my notebook and keyboard" src="https://cdn-images-1.medium.com/max/746/1*INc-jZjZKWz0igLASLN7EQ.png" /><figcaption>That’s her asking for attention regardless of what I’m doing.</figcaption></figure><h3>Conflicting Times</h3><p>Working in a team comes with ups and downs. Some of them are well known as merge conflicts. Let’s generate some for us to tinker with.</p><h4>That one branch which got merged a little too late to go clean</h4><p>Features often take a long time to be properly implemented. It’s normal. We are used to it. Our task is to implement a pet owner system so those cats can have a place to stay.</p><p>Let’s start off switching to a new branch:</p><pre>git switch -c pet-owners</pre><p>After working on it for a while, we ended up with the following diff from our original master:</p><pre>diff --git a/src/lib.rs b/src/lib.rs<br>index e179811..bf2bbb5 100644<br>--- a/src/lib.rs<br>+++ b/src/lib.rs<br>@@ -1,15 +1,34 @@<br>+#[derive(Default)]<br> pub struct Cat {<br>     pub name: String,<br>+    pub owner: Option&lt;Person&gt;,<br> }<br> <br> impl Cat {<br>     pub fn new(name: &amp;str) -&gt; Self {<br>         Self {<br>             name: name.to_string(),<br>+            ..Default::default()<br>         }<br>     }<br> <br>     pub fn meow(&amp;self) {<br>         println!(&quot;{}: Meow!&quot;, self.name);<br>     }<br>+<br>+    pub fn assign_owner(&amp;mut self, person: Person) {<br>+        self.owner = Some(person);<br>+    }<br>+}<br>+<br>+pub struct Person {<br>+    pub name: String,<br>+}<br>+<br>+impl Person {<br>+    pub fn new(name: &amp;str) -&gt; Self {<br>+        Self {<br>+            name: name.to_string(),<br>+        }<br>+    }<br> }<br>diff --git a/src/main.rs b/src/main.rs<br>index bd23920..ac36c26 100644<br>--- a/src/main.rs<br>+++ b/src/main.rs<br>@@ -1,7 +1,10 @@<br>-use hello_medium::Cat;<br>+use hello_medium::{Cat, Person};<br> <br> fn main() {<br>-    let chanel = Cat::new(&quot;Chanel&quot;);<br>+    let mut chanel = Cat::new(&quot;Chanel&quot;);<br>+    let me = Person::new(&quot;Edu&quot;);<br>+<br>+    chanel.assign_owner(me);<br> <br>     chanel.meow();<br> }</pre><p>Well, what a great day of hard work. Let’s review what we did:</p><ul><li>Created a Person struct that has a name, just for identification purposes;</li><li>Added an owner property to Cat which is optional — as in Option&lt;Person&gt;. Meaning that cats can exist without owners;</li><li>Added an assign_owner method to Cat, in which a Person is passed to it and attached to our Cat instance as its owner;</li><li>Assigned chanel to me!</li></ul><p>All looking good, its time to make the merge happen. Let’s hop back to master.</p><pre>git switch master</pre><p>Also ensure you are on the latest state of master branch.</p><pre>git pull origin master</pre><p>Since we’re dealing with a big product on the market (I guess), we pulled some commits that our coworkers worked on. Sometimes changes are just too much, so we are not spending any time to look through them.</p><p>Well, if we got any problem, we might find out right now…</p><figure><img alt="git merge pet-owners: it resulted in conflicts on both files." src="https://cdn-images-1.medium.com/max/1024/1*oq9rLEBg9JyMYotNP92_9g.png" /><figcaption>Uh-oh…</figcaption></figure><blockquote>Both files conflicted? Everything will break now. Why no one warned me they were messing with the project? Now I gotta handle this and I will mess up…</blockquote><p>It’s all right, calm down. Nothing is lost. We are here to become very efficient at handling conflicts.</p><h3>Prepare Before Actually Diving In</h3><p>A knight without a sword is nothing but a tin man. Let’s setup <em>our sword</em>, which will be Vimdiff.</p><blockquote>There is also nvimdiff, which is NeoVim’s version of Vimdiff.</blockquote><h4>Vimdiff by itself</h4><p>Now, Vimdiff is not exclusive to Git usage and it is a pretty interesting tool by itself. It can compare any files to a max of<strong> eight files simultaneously</strong>.</p><p>To show that, I’ll great a couple of files with dummy text and then let’s hop into Vimdiff real quick.</p><pre>vimdiff file-1 file-2 file-3 file-4 file-5</pre><figure><img alt="All files compared side by side with highlightings" src="https://cdn-images-1.medium.com/max/1024/1*b73p8antIU6OSDrh3e3MiA.png" /></figure><p>Pretty nice, huh? It highlights all our differences between each file just like a diff command would do, but with all the benefits of using Vim that we love.</p><p>I want to take a step further now and teach you how to manipulate files within this diff mode — which will be important when solving conflicts.</p><h4>Messing with diffed files</h4><p>To make things easier to read, I shrank it down to 2 longer files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COM4aOZS-IeQwOTuKllWbg.png" /></figure><p>We have file-1 on the left and file-2 on the right. Both with some random text. Our job is to fix them up. First thing I noticed is that we made a typo on line 6. We did notice that thanks to file-2 which has the correct spelling.</p><p>Look how easy it is to exchange <em>hunks</em> between files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXPTtvr4VraKqr1SmMceeQ.gif" /></figure><p>I have <a href="https://www.thregr.org/~wavexx/software/screenkey/">screenkey</a> on the bottom right so you can take a closer look at what I am typing:</p><ul><li>]c goes to the next hunk. In case you don’t know, a hunk is basically a <em>block of differences</em>. Our example has three of those.</li><li>:diffget fetches the other version of that hunk from the buffer we specify and applies it to our current buffer. Since file-2 buffer is opened by the right side, we simply reference it by name with diffget file-2.</li></ul><p>We skipped the first hunk in this case, but I actually want to make it so that all files say <em>good evening </em>for us. Let’s see how we do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghKggEJCTLLzlCGX-rypuA.gif" /></figure><p>Although we could do everything from file-1 buffer, I switched to file-2 just to showcase from a different perspective. Anyways, let’s break these actions down:</p><ul><li>[c goes to the previous hunk — the opposite of [c;</li><li>:buffers displays a list of loaded buffers. We use it to specify check what is file-1’s buffer specification — which is 1 because it was the first buffer to be opened;</li><li>:diffput takes the hunk of the buffer our cursor is currently onto and applies it to the specified buffer. We did that by :diffput 1 which uses file-1’s buffer ID. We could have used the file name as we did before if we want, just keep in mind those commands are versatile.</li></ul><p>When we did it, Vimdiff took both line 3 and 4 changes and applied them together onto file-1 as we told it to do. We didn’t want it, but because they are the same hunk there is no way to split it.</p><p>It even folded the rest of the files, because they are of no interest to Vimdiff anymore since they are identical from before that point.</p><p>Let’s go back and change what we want manually instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdJOxXttjnZDlzOYR6bTLA.gif" /></figure><p>Trying to undo the change while on file-2 didn’t work. We had to go into file-1 first and then go back to file-2 to make the changes.</p><p>Don’t worry. Undo still works the same. This is because file-2 was not changed when we diffput, therefore there is nothing to actually revert. I got really confused when I first faced this small inconvenience. Just keep in mind that those files are not attached, they are only being compared against each other.</p><p>Now all that’s left is that accidental “:qa” I left in the file. We already know all the commands we need, so let’s get this done with.</p><figure><img alt="Using :diffg 1 to solve the last difference on the bottom of the file" src="https://cdn-images-1.medium.com/max/1024/1*xhGFfMgVhfriGD49Z0n2PQ.gif" /><figcaption>diffg and diffpu are builtin abbreviations to diffget and diffput</figcaption></figure><h3>Defeating The Great Conflict Beast Once And For All</h3><p>Now that you are professional Vimdiff users, let’s take this power to production.</p><h4>Making Vimdiff your Merge Tool</h4><p>We can make our lives easier and let Git handle the files setup for us by configuring our mergetool command. We just need to specify vimdiff to it. Pretty straightforward.</p><pre>git config --global merge.tool vimdiff</pre><h4>Now back to our conflicted project</h4><p>To use our new powerful merge tool, we simply do:</p><pre>git mergetool</pre><p>With that, Git takes us to each conflict with a pretty interesting panel layout let us do our thing to resolve them.</p><figure><img alt="3-way merge in panels containing a base one at the bottom" src="https://cdn-images-1.medium.com/max/1024/1*ZGADaqyP3bke8cV05x5lBg.png" /></figure><p>This screen can be pretty frightening at first. What is all that?</p><p>I want you to take a moment to look at each file name. They are on the bottom of each panel.</p><p>Keep them in mind, they are very important to distinguish them. Those names may or may not ring a bell to you, but let’s break it down to make it clearer.</p><p>Take a look at the top row first. What matters to us are the middle term of each: LOCAL, BASE and REMOTE. Each of them represent a state of our file.</p><ul><li>REMOTE — Our feature branch (pet-owners in this case). It shows the incoming changes from the branch that we are trying to merge into master;</li><li>LOCAL — Target branch (master). Its the current state of the file that we’re trying to merge our changes <em>into;</em></li><li>BASE — Common ancestor. This means that we’re seeing the last most recent commit in which both branches have in their history. That’s before the diverging point. It’s LOCAL and REMOTE’s last identical commit to this file;</li><li>src/lib.rs — Working-tree. It doesn’t have any special term because it is the actual file that currently resides in our file system. We want to apply changes to <em>this</em> file in order to resolve conflicts and continue the merge, as we can see by the markers.</li></ul><p>At this point we are already pretty knowledgeable of the primary functionalities Vimdiff has to offer and we are aware of what each panel represents. All that’s left is to sort out our project in the desirable way.</p><p>Because we are working to fix the bottom file — the one that matters, top ones are references — we’ll keep our cursor on there the entire time, just for the convenience of being on our true file.</p><p>First things first, let’s browse through the diffs to get a grasp on what is going on from a macro perspective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QxHAXRwl_yAGjjj2FLBqAw.gif" /></figure><p>It’s important to know that [c and ]c <strong>won’t jump specifically through conflicts</strong>. Any change from BASE will be included here. As you can see, the last hunk of change is nothing more than additions to the file and don’t have markers indicating such.</p><p>We should keep our eyes open for those <em>HEAD</em> and <em>feature branch </em>markers that start conveniently highlighted as yellow due to their conflicted nature. There is no default binding for jumping through conflicts though. Plugins like <a href="https://github.com/tpope/vim-unimpaired">unimpaired</a> offer those bindings for us — but we won’t be using it.</p><p>Anyway, we have two conflicts happening on this file. Apparently, our coworkers took preliminary actions while our feature wasn’t ready by tracking which cats are wild with a is_wild flag.</p><p>We probably won’t need it anymore, so we’re only keeping our changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4psTivN4zWOqlVD5I6yfuA.gif" /></figure><p>As I mentioned before, diffget is a versatile command. In the GIF above I did each conflict resolution by different specifications: REMOTE and RE.</p><p>This abbreviation also works for the other buffers as in:</p><ul><li>LO for LOCAL;</li><li>BA for BASE;</li><li>RE for REMOTE as we&#39;ve already seen.</li></ul><p>It saves us nothing more than 2 to 4 characters in these cases, but it is pretty damn convenient they exist and I personally use it all the time.</p><p>Once we finish it, just :wqa to exit. The intermediate files on the top row are temporary, so don’t worry about saving them to the working-tree by mistake. When we do it, Git immediately takes us to the next conflicted file.</p><p>Let’s move on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UkUUFVr1vQonMg8K0r_liA.gif" /></figure><p>For the main.rs file, we opted for the LOCAL changes instead of ours. Although controversial, it might be more practical for our team to import it all, right?</p><p>Our merge went smoothly and our history looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*nBEXdbNI0KzqlSjt2a0qIg.png" /></figure><h3>Conclusion?</h3><p>Now that we have mastered Vimdiff and solving conflicts… Oh. Actually there is another matter we need to talk about.</p><h3>Is There Anything Out There?</h3><p>My prompt kind of spoiled it, but let’s stop to do a git status for a moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZoLidBTQGlTviZQXlrinHw.png" /></figure><p>When using mergetool command, Git saves a backup of the original conflicted state of the files. We can further ensure it by inspecting it:</p><pre>&lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD<br>use hello_medium::*;<br>=======<br>use hello_medium::{Cat, Person};<br>&gt;&gt;&gt;&gt;&gt;&gt;&gt; pet-owners<br><br>fn main() {<br>    let mut chanel = Cat::new(&quot;Chanel&quot;);<br>    let me = Person::new(&quot;Edu&quot;);<br><br>    chanel.assign_owner(me);<br><br>    chanel.meow();<br>}</pre><p>You can see it is the same as it was when we first entered the conflicted file through Vimdiff. Don’t ever commit those files. They are useless for the code base and will do nothing but clutter your work-tree and history altogether.</p><h4>How to avoid .orig files</h4><p>There are ways around it though. We can straight up disable the backup files — which I recommend — by using the following config command:</p><pre>git config --global mergetool.keepBackup false</pre><p>If you find it useful for some reason, you can simply add below to .gitignore:</p><pre>*.orig </pre><p>I’d love to hear an argument in favor of the .orig files though, because I just see them as dirty in my work-tree.</p><h3>Conclusion</h3><p>Now that we have mastered Vimdiff and solving conflicts it is much easier to work around them. I hope this article helps you become more comfortable around those situations, because I had my time where I would paralyze upon causing a conflict.</p><p>Git is an amazing tool which forces me to learn something new everyday, and combining it with Vim just makes the whole experience much nicer.</p><p>Since I wanted to show you a universal and very minimally configured environment I opted to do this entire article in Vimdiff, but you can also go straight into nvimdiff like I do, which is the same tool but using NeoVim as its base.</p><p>You can be certain that I’ll be coming back with more on (Neo)Vim, Git, and programming in general. It is simply a delight to just pick a subject and dig into it to later spread everything I learned.</p><p>Make sure to follow me so you don’t miss future content, and happy merging!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71df98d4a84c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dual Keyboard Layout From Scratch]]></title>
            <link>https://medium.com/@EduardoRodriguesF/dual-keyboard-layout-from-scratch-30dad3f2d854?source=rss-3c232a2263b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/30dad3f2d854</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[xorg]]></category>
            <category><![CDATA[keyboard-layout]]></category>
            <dc:creator><![CDATA[Eduardo Rodrigues]]></dc:creator>
            <pubDate>Wed, 03 May 2023 10:57:08 GMT</pubDate>
            <atom:updated>2023-05-03T10:57:08.770Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Lego character holding a keycap on top of a keyboard" src="https://cdn-images-1.medium.com/max/1024/1*NYwMyzfD9nGNS6IwdywJjQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kensuarez">Ken Suarez</a> on <a href="https://unsplash.com/photos/4IxPVkFGJGI">Unsplash</a></figcaption></figure><p>Many of us who have English as their second language come to the situation of having two keyboard layouts into their daily workflow: <strong>your native language’s and the US layout</strong>.</p><p>I recently started using i3 tiling window manager, and as the lightweight option as it is, it doesn’t come with any GUI for setting system configurations, which can be a pain for early Linux adopters.</p><p>During my transition to i3 I had some trouble configuring a persistent dual keyboard layout configuration, so I figured I would write that article in case someone else gets in the same problem.</p><h3>Into Some Context</h3><p>When it comes to keyboard layouts, my muscle memory breaks into two:</p><h4>Communication</h4><p>When it comes to communication — either a formal email or a casual talk to friends — it has to be my good old Brazilian layout. Otherwise it would be impossible to type things such as “ç” or “é”.</p><figure><img alt="Brazillian keyboard layout" src="https://cdn-images-1.medium.com/max/1024/0*MKE9VIIZW3zwAzkr.png" /><figcaption>Brazilian</figcaption></figure><p>Writing texts in Portuguese is part of my routine, so I need this one ready to go.</p><h4>Terminal and Coding</h4><p>On the work side, the US layout makes for a much more comfortable experience in my option. That’s mainly because of the position of semicolon (;) and quotes (“/’). Having those keys on the home row really makes a difference.</p><figure><img alt="American keyboard layout illustration" src="https://cdn-images-1.medium.com/max/1024/1*OsGJksTGG1ZeEtf-QBkQYw.png" /><figcaption>American</figcaption></figure><h3>My First Troublesome Approach</h3><p>It was pretty quick for me to find setxkbmap command which allows me to do a simple command to determine the layout(s) I’d have configured:</p><pre>setxkbmap -layout &quot;us,br&quot;</pre><p>I also figured a command to set a binding to actually switch between those two layouts:</p><pre>setxkbmap -option &quot;grp:win_space_toggle&quot;</pre><p>Now I could easily switch between US and BR layout with Super+Space keys. However, if you tried that out you would eventually realize that this configuration is only for the current runtime — it gets lost on every boot.</p><p>I turn my computer off every night, so I needed a persistent configuration.</p><h3>The Right Way</h3><p>This is not distro-specific, but ArchLinux’s documentation really helped me on this one. They show an example on <a href="https://wiki.archlinux.org/title/Xorg/Keyboard_configuration">this page</a> that’s exactly what I was going for.</p><p>What we have to do is create a file at /etc/X11/xorg.conf.d/. The file name is arbitrary and I’ll go deeper into that later, but let’s go with 00-keyboard.conf just like the documentation suggests. We’ll use this file to define some options for any keyboard that our system detects.</p><p>Let’s quickly use Vim to create and edit this new file:</p><pre>sudo vim /etc/X11/xorg.conf.d/00-keyboard.conf</pre><p>For my setup, I configured it the following way:</p><pre>Section &quot;InputClass&quot;<br>        Identifier &quot;system-keyboard&quot;<br>        MatchIsKeyboard &quot;on&quot;<br>        Option &quot;XkbLayout&quot; &quot;us,br&quot;<br>        Option &quot;XkbOptions&quot; &quot;grp:win_space_toggle&quot;<br>EndSection</pre><p>Notice that we configured the same options as we did with setxkbmap with a slightly different syntax.</p><h4>Understanding The File</h4><p>I find it very uncomfortable to follow through something that I’m not sure what is doing, so I’ll break this down so you don’t have to.</p><p>The xorg.conf.d directory contains startup configuration files that X11 server will use. So anytime we launch GNOME on Xorg, or i3 in my case, those files are being used.</p><p>.conf Files are loaded in alphabetical order, so it is convenient to create them with numbering prefix to make ordering easier. Other than that, they don’t really matter. Unless I am doing some pretty specific configuration, I’d simply stick with what the documentation implicitly suggests.</p><p>Each file can have multiple classes defined. In our case, we define a single class. The Identifier entry is technically the only one required. This specifies an unique name for the inputs that match our class — we set it as system-keyboard as the documentation I referred before does, but could be any other.</p><p>Inside our InputClass section, we must specify which will be our criteria for a device to be considered a system-keyboard class. Since we want all our keyboards to follow these standard, the only entry we use will be MatchIsKeyboard as on.</p><p>we also defined Option entries that gives the options we are passing through the devices as soon as they connect. As I mentioned earlier, we have the two options we defined before using setxkbmap:</p><ul><li>XkbLayout — Keyboard layout(s)</li><li>XkbOptions — This one can receive many options, but we just want an easy way to alternate between layouts, so we pass grp:win-space-toggle.</li></ul><p>If you want to see another .conf example, I also have a 50-mouse-acceleration.conf in my machine:</p><pre>Section &quot;InputClass&quot;<br>        Identifier &quot;Mouse&quot;<br>        MatchIsPointer &quot;yes&quot;<br>        Option &quot;AccelerationProfile&quot; &quot;-1&quot;<br>        Option &quot;AccelerationScheme&quot; &quot;none&quot;<br>        Option &quot;AccelSpeed&quot; &quot;-1&quot;<br>EndSection</pre><p>It’s pretty simple as well, It’s basically acceleration configurations for my mouse in general.</p><h3>Final Thoughts</h3><p>Having dual keyboard layout setup is very important for some of us. I hope this article helped you not only make it work, but also understand how we configured that.</p><p>After going through that, you should have it already configured right away every time you reboot.</p><p>I find that setting configurations in those .conf files is much preferable than through GUIs, since it gives us a pretty consistent way to set it up across any number of machines to create consistent workflows.</p><p>All the explanation I gave can be found on <a href="https://www.x.org/releases/X11R7.7/doc/man/man5/xorg.conf.5.xhtml">Xorg documentation</a>, in case you want to dive deeper into this knowledge.</p><p>If you find that another method is better, I would also love to hear about it. Anyway, I hope to see you around another time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30dad3f2d854" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WSL — Why I Switched To Linux]]></title>
            <link>https://medium.com/@EduardoRodriguesF/wsl-why-i-switched-to-linux-b879994b9cee?source=rss-3c232a2263b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b879994b9cee</guid>
            <category><![CDATA[i3wm]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[wsl]]></category>
            <category><![CDATA[windows]]></category>
            <dc:creator><![CDATA[Eduardo Rodrigues]]></dc:creator>
            <pubDate>Mon, 01 May 2023 08:02:15 GMT</pubDate>
            <atom:updated>2023-05-01T08:02:15.648Z</atom:updated>
            <content:encoded><![CDATA[<h3>WSL — Why I Switched To Linux</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*cyNFqdmlify_d3cv_SWr1A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lukash">Lukas</a> on <a href="https://unsplash.com/photos/NLSXFjl_nhc">Unsplash</a></figcaption></figure><p>Programming in Windows is okay at most. I guess the majority of you would agree that developer experience in Linux is better. However, the transition to Linux can be quite annoying.</p><p>When I say annoying, I really mean it. I’ve run into a couple of odd troubles myself:</p><ul><li>Not being able to share my screen (Google Meets, Discord…);</li><li>Chromium-based browsers crashing all the time;</li><li>GPU drivers installation is tricky, <a href="https://www.youtube.com/watch?v=RwnRsPBi88c&amp;ab_channel=KIMI">specially for Nvidia</a>.</li></ul><p>They are mostly on-point problems, but when you are trying to get a reliable setup to work they can be huge drawbacks.</p><h3>I Tried To Like Linux And Failed</h3><p>The year was 2019, I was still relatively new to programming and wanted to try out Linux.</p><p>Said and done. I setup a dual-boot with Ubuntu and was decided to do all my projects there while personal stuff would be on my Windows — specially gaming.</p><figure><img alt="Ubuntu 20.04 out-of-the-box desktop screenshot" src="https://cdn-images-1.medium.com/max/1024/0*yKK5wA1lHyT_rZnJ.jpg" /><figcaption>Ubuntu 20.04</figcaption></figure><p>As I mentioned early, I still was in my early programming days. I didn’t really understand how Linux works, as a consequence <strong>I didn’t make it my own</strong>.</p><p>I wasn’t generally happy with the GUI experience when compared to Windows, but I had no clue what I could do about it. I was simply going for the default experience Ubuntu provided with the GNOME desktop environment — another term I didn’t know what meant.</p><h4>The Urge for Up-to-date</h4><p>I really appreciate having the</p><p>Ubuntu is a very stable system. It takes quite a long time to get updates because of such, which always bothered me. As soon as a new release came out, I searched on how to get the update.</p><p>It was a disaster. I had an AMD graphics card by the time and its drivers were not compatible with that newer version yet. I basically couldn’t have the right drivers anymore.</p><p>After a couple days trying to work this out, I simply gave up. Rolled back to the previous version and moved on. Everything got back to work as it used to, but this left me with a bittersweet taste about Linux in general. Eventually, I came back to exclusively using Windows again.</p><h4>The First But Not Last</h4><p>Even though I backed out this time, I still came back to Linux a couple more times. I gave two other chances to Ubuntu, and one time I tried to get used to Manjaro.</p><p>It never clicked. Windows was always the most comfortable environment for me and it was really hard to change it after using it since forever. If only there was something that unifies the general Windows experience with the Linux system as a whole…</p><h3>Make Way for WSL2</h3><p>The Windows Subsystem for Linux changed everything. It takes the best out of both operating systems for a great development experience. If you haven’t ever used a Linux Shell, WSL2 is the perfect place to start.</p><p>While using a distro gets you a Linux as is, WSL2 really helped me see Linux purely through the terminal. What I mean by that is, although I <em>can</em> access the subsystem via Window’s file explorer, it is simply more practical to learn to manipulate it through the terminal itself.</p><p>Having this perception allows you to come up with neat solutions for very specific problems. Speaking of which, my first Medium article was about one issue that certainly most people wouldn’t even think existed.</p><p><a href="https://betterprogramming.pub/developing-rust-games-in-wsl-677cd1f37bc1">Developing Rust Games in WSL</a></p><p>If you’ve read it you’ll know that I actually use <a href="https://github.com/yuk7/ArchWSL">ArchWSL</a>. It really helped me come around the Up-to-date urge I brought up earlier thanks to its package manager — <a href="https://wiki.archlinux.org/title/pacman">pacman</a>.</p><h4>The Not-so-great Aspect</h4><p>My personal laptop is pretty great for WSL2. It has an Intel i7–1165G7 and 16GB RAM. I am specifying those because I want to highlight that <strong>I basically have no memory-related issues here</strong>.</p><p>By that time, I was using the same laptop on personal and work situations. In my opinion, this is not ideal. I did so because the company laptop was pretty old and slow — even a basic Git Bash workflow was too much.</p><p>Eventually, it got upgraded to a much better one with Intel i5–1135G7 and 8GB RAM.</p><p>When I received it, I could finally get rid of every work-related stuff from my personal laptop and use the company one for work. Unfortunately that brought some drawbacks to the table.</p><p>WSL2 uses Hyper-V under the hood to create the virtualization for the Linux environment. It’s way more lightweight than an actual virtual machine, but it still comes at a cost.</p><p>When I have a Chromium browser, Discord, Insomnia and one or two WSL2 tabs on Windows Terminal, things start feeling very slow. Midway through the day you can already see it becomes unusable after a certain point.</p><figure><img alt="Task manager screen showing WSL using almost 3GB RAM, making the total memory usage go to 85%" src="https://cdn-images-1.medium.com/max/782/1*Ei4tiQTNJUamSTv7Q1URhw.png" /></figure><p>The terminal starts suffering to get you an output, all inputs become highly delayed, and the whole Windows becomes painfully slow.</p><h4>There Will Be Drawbacks, But I Endured</h4><p>Even though those memory usage problems would actually get on my way of getting work done, I’d still use it for quite a while. I really liked to work within Linux and I couldn’t go back to pure Windows anymore.</p><p>I am actually thankful I kept using it. It gave me time to learn about Bash as a programming language, effectively using the package manager, and even knowing the tools I liked in my terminal experience.</p><p>I even talked about those on another article I wrote a few days ago.</p><p><a href="https://medium.com/@EduardoRodriguesF/great-command-line-tools-on-my-daily-workflow-9993c4cfe8cf">Great Command-line Tools On My Daily Workflow</a></p><p>It has been more than a year I am into WSL2 already, and I became very proficient working mostly within the terminal. The GUI started to come second for me.</p><h3>When Something Is Lacking</h3><p>The most important reason I started using WSL2 in the first place was productivity. Although I persisted with, the memory usage thing was really holding me back on that matter.</p><p>Once I remembered my real motivations, I came with a more on point objective: <strong>I needed a lightweight workflow</strong>. I knew it would be impossible to do it the way I wanted on Windows, so I chose Manjaro with GNOME for the job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RH9h_qi5fur120P4.png" /><figcaption>Screenshot from <a href="https://www.gamingonlinux.com/2021/08/manjaro-linux-2110-pahvo-is-out-with-installer-improvements-new-desktop-upgrades/">GamingOnLinux article</a> by <a href="https://www.gamingonlinux.com/profiles/liamd/">Liam Dawe</a></figcaption></figure><p>If you are a Linux for a bit longer than I you are already wondering why I chose GNOME, since it’s not exactly the most lightweight DE out there.</p><p>I needed a place to start. I know I’ll eventually take the time to get a pure ArchLinux and install everything from scratch — from creating the disk partitions to installing my own bootloader — but I just needed to get started.</p><p>GNOME would be perfect, since I already used it in my previous Ubuntu iterations. All I’d need to do was get my hands dirty with customization to make the perfect desktop for myself.</p><h3>The Struggles Along The Way</h3><p>When I reached this point, I was already pretty comfortable with the terminal itself. My configurations were solid, so I had all that out of the way — that’s a benefit only WSL2 could give me upfront.</p><p>Now I only had to sort out the desktop and system stuff for me to get the perfect development environment. It has not been an easy transition, I must say. I’m learning a lot though.</p><h4>Wayland? X11? Why Does It Matter?</h4><p>This could be an article by itself, but those guys gave me a lot of headache. They are both <em>window system protocols</em>, and while Wayland is supposed to be a much more modern approach, it’s still unstable for some cases.</p><p>The actual trouble I ran across was pretty specific: I was unable to share my screen on any application. This is a big deal for me because I often have to do so in client meetings or simply to help out my coworkers.</p><p>I searched many places for a way to solve it but none worked for me. Although I would love to stick with Wayland, I still don’t find it to be worth it because of those unsupported features.</p><p>Once I understood that those two protocols were, it was simple enough to switch to the stable X11 back. Problem solved, for now.</p><h4>Chromium-based Browsers Crashing</h4><p>My favorite browser is Microsoft Edge, so this issue was pretty huge for me. And honestly, I am still struggling with that one.</p><p>In my personal laptop I don’t have much problem with that. As a matter of fact, I am using Edge right now to write this article. But the company laptop still struggles, so there I am temporarily going with Firefox.</p><p>This issue is probably associated with memory usage again — Chromium-based application are very memory hungry — so learning how to manage memory in my Linux machine is high on my to-do list. I might share my discoveries with you whenever I come around it.</p><h3>How It Turned Out So Far</h3><p>It is still a work in progress, but my setup is getting pretty interesting shape so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sVw6SOWHfMvMK-ezSeflCw.png" /></figure><ul><li><a href="https://i3wm.org/">i3-wm</a> with <a href="https://github.com/polybar/polybar">polybar</a>, <em>check</em></li><li><a href="https://github.com/tmux/tmux/wiki">tmux</a>, <em>check</em></li><li>Utilities such as <a href="https://github.com/ajeetdsouza/zoxide">zoxide</a>, <a href="https://github.com/ClementTsang/bottom">bottom</a>, <a href="https://github.com/dylanaraps/neofetch">neofetch</a>; <em>check</em></li></ul><p>Using i3 makes for a much more organized window setup. It is also lightweight and stable, so it is the perfect choice for my situation.</p><p>Getting in touch with all these amazing tools have been great for me to actually discover my taste for development environments. All of that made me realize how much Linux has to offer outside the out-of-the-box experience.</p><p>After all this setup, the company laptop is handling everything much smoother than before. I no longer have slow downs midway through my work, which is enabling me to be much more productive.</p><h3>A Halfway Conclusion</h3><p>After many tries, I finally managed to (better) understand the Linux environment and make it my full-time workspace.</p><p>WSL2 really helped me a lot, and I think I would have a much more difficult transition if it wasn’t for it.</p><p>I still have a lot to discover. I want to dive much deeper, so I am certainly bringing more articles to tell my experience in the next days or weeks. For that, you can <a href="https://medium.com/@EduardoRodriguesF">follow me</a> to be updated whenever I post a new article.</p><p>Hope to see you around soon. Have a happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b879994b9cee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Should Rely More On Your Terminal]]></title>
            <link>https://medium.com/@EduardoRodriguesF/you-should-rely-more-on-your-terminal-f4435139f7a?source=rss-3c232a2263b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4435139f7a</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[shell]]></category>
            <dc:creator><![CDATA[Eduardo Rodrigues]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 08:02:10 GMT</pubDate>
            <atom:updated>2023-04-26T08:02:10.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*S-JzIofFmtW8Zp2KWaEVIQ.jpeg" /><figcaption>Sorry about this Emacs there, I already got rid of it.</figcaption></figure><p>The advent of GUI tools made us feel comfortable far from the shell. In this article I want to convince you that you should give a chance for your terminal.</p><p>A few days ago I wrote an article about my experience with Vim.</p><p><a href="https://medium.com/@EduardoRodriguesF/the-groundbreaking-vim-experience-88b267dd2f67">The Groundbreaking Vim Experience</a></p><p>Although I primarily focused on text editors and the process of writing code, there is another huge topic I didn’t talk about in there — the reliance on the terminal.</p><p>GUI was what made computers become accessible for personal usage, and naturally the same happened to the development scene. <a href="https://desktop.github.com/">GitHub Desktop</a> makes Git so much easier, file explorers are practical; but those will never be as reliable and flexible as the classic command lines.</p><p>Once I started using Vim, I naturally became more attached to my terminal. It made me realize how much I was missing out. Today, I am going to show you the great things you can accomplish within your terminal.</p><h3>The Frightening Power of A Shell</h3><p>The Shell is the bridge between you and the Kernel. It’s hard, I get it. For an untrained eye, it is really messy to work on screens like this:</p><figure><img alt="Executing top command on a linux terminal." src="https://cdn-images-1.medium.com/max/1024/1*r40HX6doCLDWo-uUs9nXew.png" /><figcaption>Command: top</figcaption></figure><p>And how am I supposed to navigate through my files this way?</p><figure><img alt="Executing listing of files in a Linux terminal." src="https://cdn-images-1.medium.com/max/1024/1*yxeTugiPITCA8YYY23qlag.png" /><figcaption>Command: ls -lah</figcaption></figure><p>I think everyone has these same thoughts when introduced to a shell like this. Many of those tools were there on the early programming days — they were not exactly designed with UX (or should we say DX?) in mind. Despite the appearance issue, <strong>they are the only way to use your system to the fullest.</strong></p><h4>It Doesn’t Need To Be Ugly</h4><p>The screenshots I showed you early are not what I use on my workflow. The terminal is your canvas, and once you learn your tools you can go on and customize or replace them the way you want.</p><p>So yes, there are some command line tools that I use just for the sake of appearance. In my ZSH configs, ls is an alias for <a href="https://github.com/ogham/exa">exa</a>, which is a <em>modern replacement for </em><em>ls </em>— as described in Exa’s README file.</p><figure><img alt="exa — icons -lha command" src="https://cdn-images-1.medium.com/max/1024/1*ittTByE9w31YWSndz78X2Q.png" /><figcaption>Exa looks way better</figcaption></figure><p>You can see I used a lh command, but this is actually an alias for the following:</p><pre>exa --icons -lha</pre><p>The same goes for processes management too — which top is the default tool — is not on my tool chain neither. For that purpose, I use <a href="https://github.com/htop-dev/htop">htop</a>.</p><figure><img alt="htop command in terminal showing the processes on my machine" src="https://cdn-images-1.medium.com/max/1024/1*J73UpI3PL96M0a6DNpaq8Q.png" /><figcaption>Command: htop</figcaption></figure><p>There are other alternatives as well, but I am really growing to love<a href="https://github.com/ClementTsang/bottom">bottom</a>, which has me letting it opened in a Tmux session the entire time:</p><figure><img alt="btm command display" src="https://cdn-images-1.medium.com/max/1024/1*8BMdtjOEffhO1upT89BaJQ.png" /><figcaption>Wow! Even prettier.</figcaption></figure><p>If you don’t like how something looks, I am certain you’ll find one that fits your eyes just right. I didn’t even talk about the prompt looking itself — which I use <a href="https://starship.rs/">Starship</a>.</p><h3>Now Comes The Amazing Part</h3><p>Sure, we got ourselves a nice looking command line interface. Now what? Where is all the power that I advertised for you? Wait no more! Let’s get to some examples so you can get the idea.</p><h4>Searching Stuff Up</h4><p>My home directory is filled with configuration dot-files, and more often than not I end up needing to edit a file that I can’t remember exactly the name.</p><p>I could open file explorer and use the search mechanism, but maybe it is not showing my hidden files, then I’ll have to look for how to enable them… There is an objectively better way.</p><p>Bash has this command called grep which exists for exactly this purpose. Imagine you need to edit your ZSH file but you can’t quite remember its name. Worry no more! We can list all our files and <em>pipe</em> (|) the output to grep.</p><figure><img alt="Executing “lh | grep ‘zsh’”" src="https://cdn-images-1.medium.com/max/541/1*36FpHNhwIwYkHJ63QA5bsQ.png" /></figure><p>Let’s break it into parts:</p><ul><li>We list all the files and directories we have using lh;</li><li>The | will get the output of the command on the left and <em>pass to the standard input </em>to the command on the right.</li><li>grep will search for the term “zsh”, the content of its search is coming from lh.</li></ul><p>Use your imagination for a moment, imagine how much you can do with this syntax.</p><p>I have this game prototype project with a fair amount of commits. Let’s say I want to pick the commits I did related to player input. grep is on the rescue!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*zHHH52HKTYPdtMxWBzQwpw.png" /></figure><p>We can go a step further and install another command line tool called <a href="https://github.com/junegunn/fzf">FZF</a>. fzf is a general-purpose command-line fuzzy finder. It is also <strong><em>blazingly fast</em> — </strong>as they state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mo16vyfrH9kIICUzVZezA.gif" /></figure><p>Beautiful, right?</p><p>Also, remember that I said you have the power of replacing anything you want? Master <a href="https://github.com/BurntSushi">BurntSushi</a> came up with a reimplementation of Grep which promises to be generally faster than Grep.</p><p><a href="https://github.com/BurntSushi/ripgrep">GitHub - BurntSushi/ripgrep: ripgrep recursively searches directories for a regex pattern while respecting your gitignore</a></p><p>We could use it instead the classic Grep for the same purpose. Let’s do the same search we did previously using both Grep and Ripgrep so we can see the visual differences:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10gQmb43RIqC6b96DLroZQ.png" /><figcaption>Ripgrep is awesome!</figcaption></figure><p>Notice how nicely Ripgrep — rg command — highlights the matching term within the message, very convenient for when we have walls of text that the tool extracted.</p><p>Since I have just a few commits in this repository, the speed improvement was very minimal. It really shines when doing recursive searches, though.</p><h4>Piping More Commands</h4><p>We can go yet another step further with this last example. Suppose I need to revert a specific commit — which I first need to find. We can also pipe those up. In fact, we can pipe as many commands as we want!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OK5mvlS2etKVP2KWDE69mQ.gif" /></figure><p>Okay, this one is a bit more complex than what I’ve shown until this point, so let’s break it down as well:</p><ul><li>git log --oneline — Lists all commits in a one line format;</li><li>fzf — The Fuzzy-finder mechanism we talked about earlier;</li><li>xargs -n 1 git revert — The command we want to execute. We tell Xargs to take one argument at a time.</li></ul><p>This last one might be a little confusing, so I wrote a whole <a href="https://medium.com/@EduardoRodriguesF/xargs-what-is-it-when-to-use-it-fcc982fb9969">article about Xargs</a>. If you don’t fully understand that command utility, I highly recommend checking it out!</p><p><a href="https://medium.com/@EduardoRodriguesF/xargs-what-is-it-when-to-use-it-fcc982fb9969">Xargs — What Is It? When To Use It?</a></p><p>In the end, Git couldn’t revert our commit due to conflicts we would have to resolve. Now we are in that REVERTING state.</p><h4>File Management</h4><p>When embracing the terminal, managing your files in it is just the natural path. You don’t want to be changing between file explorer and shell all the time, and syncing those up so you do your compiler and other CLI stuff on the terminal and mess with files in the explorer.</p><p>Believe me, I have been there. Using just the shell is enough.</p><p>File operations exists way before convenient window file explorers do. cp for copying and pasting files around. mv to <em>move</em> them. Say you have a directory and you want to copy some files out. Simple enough!</p><pre>cp foo/file1.txt bar/</pre><p>That way we copied file1.txt to bar/ directory. We can even move multiple files at once.</p><pre>cp foo/file1.txt foo/file2.txt foo/image.jpg bar/</pre><p>Any number of files is acceptable. The last path on the list will be to where your previous files or directories will be moved to. The same rules applies to mv.</p><p>Using mv even allows us to rename files.</p><pre>mv foo/file1.txt foo/descriptive-name.txt</pre><p>Most commands on Linux which handle files accept glob expressions. If we had too many files within a file, we can move them all at once.</p><pre>mv foo/* bar/</pre><p>If bar/ doesn’t exist, why not simply renaming foo/ then?</p><pre>mv foo/ bar/</pre><p>Time for a more complex action again. Let’s say we want to move all files to bar/, except those with “ba” in the name.</p><p>We’ll go with Ripgrep for that, it’s just better! But we’ll actually use -v to invert the pattern. This means that, if the file contains the pattern we specify, it will be excluded from the output.</p><p>And, since I have icons configured in an ls alias, I’ll use exa just to avoid those icons to interfere with the commands.</p><pre>cd foo<br>exa | rg -v &#39;ba&#39; | xargs -I{} mv {} ../bar</pre><p>We first cd into the directory so we can work closely with those files. Ripgrep will take care of filtering those files out. Xargs will execute mv {} ../bar for each outputted file, being {} where the arguments will be positioned.</p><h4>Navigation With Zoxide</h4><p>We all know cd. It’s the default way of changing your current directory. I want to show you the better cd.</p><p><a href="https://github.com/ajeetdsouza/zoxide">GitHub - ajeetdsouza/zoxide: A smarter cd command. Supports all major shells.</a></p><p>As its description suggests: <em>zoxide is a smarter cd command</em>. It does it by saving your most accessed files and making it possible for you to jump through the usage of key words.</p><p>I’ll use my own example. I have a folder that’s located ~/projects/games/duel_prototype. It’s not super nested as other folders might be, but it takes an effort to type it all out. After installing Zoxide, I’ll navigate just like with cd, but we’ll use the z command.</p><pre>z ~/projects/games/duel_prototype</pre><p>The big deal comes once we try to access this path later on. This time, we can type the name of the folder we want to go — but <em>partially</em>. All the commands below would manage the same thing:</p><pre>z duel_prototype<br><br>z duel<br><br>z games duel<br><br>z duel prototype<br><br>z due</pre><p>I can just type the folder name, the partial name, small parts of the path to get there… The possibilities are enormous. It uses fuzzy finding under the hood, explaining the flexibility.</p><p>For my personal laptop, it’s not much of a gain. But at my job I have different folders for ongoing clients, new comings, internal tools and VTEX’s open-source applications. It is a pain to have to type the entire path, and even the name is uncertain to me at times.</p><p>With Zoxide, if I am messing with one project at ~/really/nested/project/ and I want to go all the way back to ~/also/very/nested/big-project/, it is as simple as doing that:</p><pre>z big project</pre><h3>Real-life Examples</h3><h4>Comparing Files</h4><p>A very interesting practical example happened about a week or so at my company. We work with <a href="https://developers.vtex.com/docs/guides/vtex-io-documentation-vtex-io-cli-installation-and-command-reference">VTEX CLI</a> on a daily-basis, which allows us to manipulate an ecommerce’s account in <a href="https://vtex.com/">VTEX</a> platform.</p><p>I won’t share details on the issue, but let’s follow with this briefing:</p><blockquote>A client’s website was going through unexpected behavior. We thought that maybe upgrading the dependencies would work this out. However, we were afraid that this could come up with more problems.</blockquote><p>Listing dependencies using the CLI is easy, just do vtex ls. Upgrading is also pretty straightforward, vtex upgrade and done.</p><p>As mentioned in the briefing above, were a bit skeptical that something could break in the process, and we needed to keep track of what actually updated in order to pin specific dependencies versions if anything goes wrong.</p><p>Since I have the most proficiency with command lines among my coworkers, I took the lead on the way we approached this issue.</p><p>First, we saved the current state of vtex ls.</p><pre>vtex ls &gt; old.txt</pre><p>This redirects the output of the command on the left (vtex ls) to a file path on the right (old.txt).</p><p>Time to upgrade those dependencies now!</p><pre>vtex upgrade</pre><p>Upon finishing, let’s save the current versions again, but in a different file indicating the new state.</p><pre>vtex ls &gt; new.txt</pre><p>With both old.txt and new.txt into place, we can easily use the diff command to see what has changed between them. To make things even better, we can pass --colors just to make everything more readable.</p><figure><img alt="diff old.txt new.txt — color" src="https://cdn-images-1.medium.com/max/618/1*cLCq_vmQ3yEafH0-Yz83EA.png" /></figure><p>Now we know exactly which dependencies received an upgrade. If anything goes wrong, those will be the first suspects!</p><p>What most people would do in this situation — assuming they have similarly labeled files — would be to google “<a href="https://www.google.com/search?q=Compare+files+difference+online&amp;ei=OqtEZIqaIZDJ1sQPy5CqkAg&amp;ved=0ahUKEwiKn_jtjL_-AhWQpJUCHUuICoIQ4dUDCBA&amp;uact=5&amp;oq=Compare+files+difference+online&amp;gs_lcp=Cgxnd3Mtd2l6LXNlcnAQAzIFCCEQoAEyBQghEKABMgUIIRCgATIICCEQFhAeEB0yCAghEBYQHhAdMggIIRAWEB4QHTIICCEQFhAeEB0yCAghEBYQHhAdOgQIABBHOgYIABAWEB5KBAhBGABKBQhAEgExULgEWKIIYKkJaAFwAngAgAF1iAHGApIBAzEuMpgBAKABAcgBCMABAQ&amp;sclient=gws-wiz-serp"><em>Compare files difference online</em></a>” and find a website that does the same thing.</p><p>This is a bit of a stretch. Why go all the way to a random website filled with ads when you have a consolidated tool right in your trustworthy shell?</p><h4>Reliable Version Tracking</h4><p>I really like this example because it shows how very simple scripts can make your life so much easier.</p><blockquote>In this company CLI project, I was up to create a very simple version command like most tools have to display its current version. The problem is: from now on I would have to update the version number on both the package.json file and the index.ts where the command was being set.</blockquote><p>To work this out, I made a simple script that would generate this constant LIB_VERSION that fetches the actual version from the package.json file and writes it to src/constants/version.ts file.</p><pre>node -p &quot;&#39;export const LIB_VERSION = &#39; + JSON.stringify(require(&#39;./package.json&#39;).version) + &#39;;&#39;&quot; &gt; src/constants/version.ts</pre><p>To automate it, I simply chained that with the build script. Using &amp;&amp; syntax would cause the execution of build to stop if prebuild.sh failed.</p><pre>{<br>  // ... stuff<br>  &quot;scripts&quot;: {<br>    // other scripts<br>    &quot;build&quot;: &quot;./prebuild.sh &amp;&amp; tsc&quot;<br>  }<br>}</pre><p>Thanks to that, I never had to worry with the actual version again. The version.ts file is ignored by Git, so I don’t have to worry about it.</p><h3>Final Thoughts</h3><p>Many times a programmer’s job will consist of building solutions. For that, you should absolutely take some time to understand the one tool that is right in your computer all the time: <strong>the shell</strong>.</p><p>It might take some time to get comfortable with it, and I do plan on writing more articles on this as I absolutely love this subject.</p><p>If you are also willing to learn more, you can also follow me here on Medium to be notified whenever I publish a new article. Don’t forget to do your own research as well, though.</p><p>Thanks for reading through my article, I hope to see you more often in here!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4435139f7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Great Command-line Tools On My Daily Workflow]]></title>
            <link>https://medium.com/@EduardoRodriguesF/great-command-line-tools-on-my-daily-workflow-9993c4cfe8cf?source=rss-3c232a2263b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9993c4cfe8cf</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tooling]]></category>
            <category><![CDATA[commands]]></category>
            <category><![CDATA[command-line-interface]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Eduardo Rodrigues]]></dc:creator>
            <pubDate>Tue, 25 Apr 2023 01:08:58 GMT</pubDate>
            <atom:updated>2023-04-25T01:08:58.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5TuShIu1-ZU5l3XMT1Xfg.png" /></figure><p>Knowing your tools is argueably the best productivity booster to have in the belt. In this article I’ll show you which ones I use.</p><p>Other article writers have always made great lists like that, so I figured I would make my own!</p><p>To make it easier, I’ll break it into two sections:</p><ul><li>Replacements</li><li>Utilities</li></ul><h3>Replacements</h3><p>I think a great way to start would be listing the ones that aim to replace existing builtin tools.</p><h4>Zoxide</h4><p><a href="https://github.com/ajeetdsouza/zoxide">GitHub - ajeetdsouza/zoxide: A smarter cd command. Supports all major shells.</a></p><p>Off to a great start, Zoxide is supposed to be a “<em>smart </em><em>cd</em>&quot;, and it does the job pretty well. It works in a way that it remembers the directories you’ve been, providing you the option to navigate to them later with simple keywords.</p><figure><img alt="z entire path, then z directory name" src="https://cdn-images-1.medium.com/max/1024/1*iYHoT0SGznBXJuxhyA-F3Q.gif" /></figure><p>You don’t even need to type the entire directory name for it to work.</p><pre># This would work as well<br>z duel<br><br># Can be even more concise if I want<br>z du<br><br># Separate words work the same<br>z duel proto</pre><h4>Ripgrep</h4><p><a href="https://github.com/BurntSushi/ripgrep">GitHub - BurntSushi/ripgrep: ripgrep recursively searches directories for a regex pattern while respecting your gitignore</a></p><p>This one takes an already very useful tool — grep command — and makes it even better. It’s written in Rust, so it makes to a pretty huge performance gain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WsKIaM-_Tnw48wMGMLT8mg.png" /><figcaption>It also highlights the matched pattern by default, which is pretty convenient.</figcaption></figure><p>Just to show you, I made a very simple measurement where I searched for the term “<em>input</em>” recursively through my projects directory — where I got a couple ones.</p><p>To properly benchmark it, I used <a href="https://github.com/sharkdp/hyperfine">Hyperfine</a> — which we’ll talk about later too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__Caj7sLxxUuk3d1HbR8DA.png" /></figure><p>To search for the same pattern across all my projects, Ripgrep managed to be <strong>almost 12 times faster than </strong><strong>grep</strong>, which is pretty impressive! I use that tool all the time to search through files and get specific command output information.</p><h4>Exa</h4><p><a href="https://github.com/ogham/exa">GitHub - ogham/exa: A modern replacement for &#39;ls&#39;.</a></p><p>This one is also written in Rust. It gives the classic ls a much nicer appearance by adding icons and colors based on each kind of file.</p><figure><img alt="Output for exa — icons" src="https://cdn-images-1.medium.com/max/1024/1*oSRN2FkqmNTEBlMHT1dFXw.png" /></figure><p>Itt makes the permissions table much easier to read too:</p><figure><img alt="Output for exa — icons -lha" src="https://cdn-images-1.medium.com/max/1024/1*6CKkDSvsHde6IbQMv4Hzrw.png" /></figure><p>I like it so much that I actually have aliases for those:</p><pre>lh=&#39;exa --icons -lha&#39;<br>ls=&#39;exa --icons&#39;</pre><h4>Bat</h4><p><a href="https://github.com/sharkdp/bat">GitHub - sharkdp/bat: A cat(1) clone with wings.</a></p><p>Wrapping up our <em>rusty</em> section, bat aims to be a nice looking, feature-rich version of cat. It has syntax highlighting for many languages and even Git integration has made its way into the tool.</p><figure><img alt="Output for bat Cargo.toml, which has Git integrations showing" src="https://cdn-images-1.medium.com/max/1024/1*3g9hd4rzQW_ejNdBiHWR9w.png" /></figure><h3>Utilities</h3><p>We’ve seen a couple of nice tools by now, time to see new stuff.</p><h4>Hyperfine</h4><p><a href="https://github.com/sharkdp/hyperfine">GitHub - sharkdp/hyperfine: A command-line benchmarking tool</a></p><p>Since we’ve already used this one to talk about Ripgrep, hyperfine is a command line tool that allows you to benchmark command executions. You don’t exactly need to be <strong>comparing two commands</strong> — like we did previously — to make use of this utility, but also to benchmark the execution time for your own scripts.</p><figure><img alt="hyperfine on a bash script I wrote. It showed me that it takes about 2 seconds to execute" src="https://cdn-images-1.medium.com/max/1024/1*sEA4syVrThAzjD4zlVu6Tw.png" /></figure><p>This is a great way to keep track of the performance of some application you are willing to improve.</p><h4>FZF</h4><p><a href="https://github.com/junegunn/fzf">GitHub - junegunn/fzf: :cherry_blossom: A command-line fuzzy finder</a></p><p>This one is <strong>essential</strong>. it is a fuzzy finder command-line tool that serves many purposes. Think of it like an interactive grep — or ripgrep, since we are all on replacements today.</p><p>I often use it to search for specific commits that I can’t quite remember its message. I can use fzf command to <em>loosely</em> search by some keywords.</p><figure><img alt="git log — oneline | fzf" src="https://cdn-images-1.medium.com/max/1024/1*Sk5WGU9BtXWEri7TKMcmmg.gif" /><figcaption>It outputs the selected entry, so you can do all kinds of command pipeline with that.</figcaption></figure><h4>GitHub CLI</h4><p><a href="https://github.com/cli/cli">GitHub - cli/cli: GitHub&#39;s official command line tool</a></p><p>Also known as gh, GitHub CLI can do all kinds of operations on GitHub platform. Listing issues, visualizing and reviewing PRs, merging them, and much more.</p><p>One of the features I like the most is that, if you know a repo’s owner and name, It’s possible to simply use the &lt;owner&gt;/&lt;repo&gt; to interact with the repository.</p><figure><img alt="Navigating through vtex-apps/store-components repository and issues." src="https://cdn-images-1.medium.com/max/1024/1*tHXq2ghd5H4m3Z9Kd7D-bw.gif" /><figcaption>Visualizing vtex-apps/store-components and its issues.</figcaption></figure><p>I just did basic reading operations, but all Issue and PR management is possible within this CLI. For those who work with GitHub but enjoy keeping your eyes in the terminal, this is an essential tool with a vast list of possibilities.</p><h4>Tmux</h4><p><a href="https://github.com/tmux/tmux">GitHub - tmux/tmux: tmux source code</a></p><p>I am always going on and off across multiple workspaces. For such, Tmux is my ally. It is a multiplexer, so it allows you to create multiple terminal instances within a same window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IApOEvjEiUW8vGLRqc5rpQ.png" /></figure><p>It is highly configurable through .tmux.conf file, but it also supports plugins for extended functionality through <a href="https://github.com/tmux-plugins/tpm">Tmux Plugin Manager (tpm)</a>.</p><p>It has a more steep learning curve compared to the rest of the list, but it is really worth it.</p><h3>Honorable Mentions</h3><h4>NeoVim</h4><p><a href="https://github.com/neovim/neovim">GitHub - neovim/neovim: Vim-fork focused on extensibility and usability</a></p><p>It’s hard to <em>not</em> talk about it. NeoVim is my text-editor of choice, and it keeps me closer to the terminal. I’ve already talked a lot about it in another article I wrote in here.</p><p><a href="https://medium.com/@EduardoRodriguesF/the-groundbreaking-vim-experience-88b267dd2f67">The Groundbreaking Vim Experience</a></p><h4>Man</h4><p>It is impossible to memorize all the ins and outs of all those great command-line tools. But you don’t really need to. Also, this is the only builtin tool in the list that I talk about.</p><p>The man command stands for <em>Manual</em>. It gives you the manual for your most beloved tools.</p><figure><img alt="Output for man git" src="https://cdn-images-1.medium.com/max/1024/1*NYpbidYuw8p9A8GlyrwUzg.png" /><figcaption>Git Manual first lines</figcaption></figure><p>It’s perfect for checking all the possible arguments you can pass to a command. It’s simple, but essential for any Linux user.</p><h3>Final Thoughts</h3><p>Taking the proper time to carefully learn the tools you use is essential for whoever wants to keep up with productivity. I highly recommend taking a further look into the tools I mentioned.</p><p>Since I am always reevaluating my arsenal, I am also open to hear what tools you think would be worth recommending!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9993c4cfe8cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xargs — What Is It? When To Use It?]]></title>
            <link>https://medium.com/@EduardoRodriguesF/xargs-what-is-it-when-to-use-it-fcc982fb9969?source=rss-3c232a2263b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcc982fb9969</guid>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[standard-input]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Eduardo Rodrigues]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 03:07:51 GMT</pubDate>
            <atom:updated>2023-04-23T03:07:51.558Z</atom:updated>
            <content:encoded><![CDATA[<h3>Xargs — What Is It? When To Use It?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*18lCdShZ69WCYSxL82G0AA.png" /><figcaption>Cover image</figcaption></figure><blockquote>You may have come across Xargs commands, but what is it for? Today you’ll learn how it works and how to create powerful commands with it.</blockquote><h3>TL;DR</h3><p>When piping commands through the | syntax, the next command receives the output of the command on the left side via standard input. This works fine for commands like grep.</p><p>Commands like git revert &lt;commit&gt; receives <em>arguments</em>, thus we would need to prefix it with xargs in order to transform those outputs from the previous command into arguments.</p><h3>What Is Up With That Weird Command?</h3><p>If you are a beginner Linux user, or simply use Bash terminals by other means — like using <a href="https://gitforwindows.org/">Git Bash on Windows</a> — you end up searching things like “How to create multiple directories at once”. There might be many ways to accomplish that, but chances are you came across this line:</p><pre>echo &#39;one two three&#39; | xargs mkdir</pre><p>Maybe you didn’t really understand what it does, you just know that it did the job — it served the purpose you needed by the time. But if you are reading this, I guess you’re just like me and enjoys the art of understanding the tools you use.</p><p>If we take a look at Xargs’ manual page, we get the following:</p><blockquote>xargs — build and execute command lines from standard input</blockquote><p>Well, that didn’t help much.</p><h3>The Standard Input</h3><p>To understand what is really happening, we need to go into something called <em>standard input</em>. According to <a href="https://en.wikipedia.org/wiki/Standard_streams#:~:text=Standard%20input%20is%20a%20stream,all%20programs%20require%20stream%20input.">Wikipedia</a>:</p><blockquote>Standard input is a stream from which a program reads its input data. The program requests data transfers by use of the <em>read</em> operation. Not all programs require stream input.</blockquote><p>Now we are getting somewhere! Let’s look further into this by using some examples.</p><p>You may know Grep, which takes a file and a pattern — a simple string, or even RegEx — and returns the lines within that file that match that given pattern.</p><figure><img alt="grep ‘ls’ .zshrc" src="https://cdn-images-1.medium.com/max/469/1*R_dFX2ziUmJKkIHWL04RNw.png" /><figcaption>A good Grep operation. Nice and simple.</figcaption></figure><p>In this example, we passed .zshrc as an argument to Grep. It searched for the pattern &#39;ls&#39; within that file’s content. We can accomplish the exact same thing with the pipe syntax:</p><figure><img alt="cat .zshrc | grep ‘ls’" src="https://cdn-images-1.medium.com/max/469/1*-nVU3kniKonGjPWU--FGgA.png" /><figcaption>Exactly the same output as the previous image, but piping it with cat.</figcaption></figure><p>This syntax doesn’t make much sense if we already have the file we want to Grep, but it does become handy when we are Grepping a command output.</p><p>It is also possible to achieve a weird behavior by passing only one argument:</p><figure><img alt="grep .zshrc" src="https://cdn-images-1.medium.com/max/1024/1*mFIbdf03gfN9B6q0OHR6ew.gif" /><figcaption>Grep expecting inputs</figcaption></figure><p>This same thing happens if you execute xargs and nothing else. But I’ll get there in a bit.</p><p>Notice that we didn’t use Xargs in the pipe syntax. Why not using it there, while in the first command snippet we had to use xargs mkdir to execute the command?</p><p>Let’s keep on the practical approach and see what happens when we add xargs to the previous example.</p><figure><img alt="cat .zshrc | xargs grep ‘ls’" src="https://cdn-images-1.medium.com/max/1024/1*EsJDOdOWsozvLC6zVwQyjQ.png" /></figure><p>It didn’t work, but <em>why?</em></p><p>As we saw earlier, Xargs is supposed to “build and execute command lines from standard input”. What happened here is that Xargs took all of the contents of .zshrc — which were passed to Xargs via <em>standard input — </em>and passed <em>as arguments </em>to Grep.</p><p>To visualize it, we can pass --verbose to xargs (or -t shorthand) so that it prints out what it has received.</p><figure><img alt="cat .zshrc | xargs — verbose grep ‘ls’" src="https://cdn-images-1.medium.com/max/1024/1*LKosDVXxMw_BoA_KKPqbHA.png" /><figcaption>It crunched the entire file into one line.</figcaption></figure><p>Everything that we are seeing there is being passed as <em>arguments </em>to the next command. Notice that it still executed Grep normally, giving us the same error as before. Now let’s take a closer look at Grep’s manual page:</p><pre>SYNOPSIS<br>       grep [OPTION...] PATTERNS [FILE...]<br>       grep [OPTION...] -e PATTERNS ... [FILE...]<br>       grep [OPTION...] -f PATTERN_FILE ... [FILE...]</pre><p>Take a look at the second format. Grep accepts many PATTERNS, and at the end it accepts a FILE.</p><p>If we pay close attention to the verbose output in the last screenshot, we can observe that ~/.fzf.zsh is the last file path to appear on the content, thus it considers it to be the file to search <em>on</em> for all the arguments that come before it.</p><p>I am not entirely sure what it does with the rest of the arguments that come afterwards, neither why it prompted “<em>No such file or directory</em>” since the file actually exists in this path. If anyone knows the reason, I would love to hear it. Reach out to me and I might update the article as well!</p><h4>Read Operation</h4><p>But why did it “broke” when we passed only one argument? It actually is exactly the intended behavior. Grep has two ways of processing the content of which it searches into for patterns:</p><ol><li>Receiving a file as argument;</li><li>Receiving the content via standard input.</li></ol><p>When we passed only one argument, we actually passed the pattern for it to match — even if it was a file path, respecting the argument order — and it expects that the actual content is yet to come from the standard input, which is what happens when we pipe it through.</p><p>As soon as the program on the left of the pipe exits, it ends the read operation and passes the content through the next command after the pipe.</p><p>It might be weird, but it’s actually a good thing! In my <a href="https://github.com/EduardoRodriguesF/dotfiles">dotfiles repository</a> I setup the following script:</p><pre><br>#!/usr/bin/env bash<br><br>git clone --bare https://github.com/EduardoRodriguesF/dotfiles $HOME/.dotfiles<br><br>function dotfiles {<br>  /usr/bin/git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME $@<br>}<br><br>dotfiles checkout<br><br>if [ $? = 0 ]; then<br>  echo &quot;Checked out dotfiles.&quot;;<br>  else<br>    echo &quot;Backing up pre-existing dot files.&quot;;<br><br>    mkdir -p .dotfiles-backup<br>    dotfiles checkout 2&gt;&amp;1 | egrep &quot;\s+\.&quot; | awk {&#39;print $1&#39;} | xargs -I{} mv {} .dotfiles-backup/{}<br>fi;<br><br>dotfiles checkout<br><br>dotfiles submodule init<br>dotfiles submodule update<br><br>dotfiles config status.showUntrackedFiles no</pre><p>Don’t worry about the actual implementation. Just keep in mind that this script is supposed to download my repository and replace the files in the current machine with the ones that were just cloned.</p><p>With that, I also provided a command in the README to execute it at once:</p><pre>curl -Lks https://gist.githubusercontent.com/EduardoRodriguesF/600ed2f94ad4bdba947fbdf0ca698a9e/raw | bash</pre><p>So what happens is that the script’s content will be cURL’d and passed to bash as an input. It only executes the script when the response is received. This would be equivalent to downloading the Gist to a file and then running Bash with the path as argument.</p><p>This is why we are “free to type” when we omit some arguments earlier. Standard input is expecting something to <em>end</em> so that it moves on the command.</p><h3>Using Xargs The Right Way</h3><p>Now that we managed to observe the different behaviors of standard input versus arguments, we have a better understanding of what Xargs does, so we can go on to use it like masters.</p><p>Previously we saw the --verbose flag, but there are a couple of helpful arguments that we can pass to Xargs to achieve certain things. For that manner, I really encourage you to look into Xargs’ manual page and experiment with those. For the sake of that article, I will show you an example with my favorite argument.</p><p>Let’s say that we want to revert a Git commit. We actually still don’t know which commit we want to revert, so we’re going to search for it using <a href="https://github.com/junegunn/fzf">FZF</a>. After finding, we want to execute git revert to do the job. You might initially think of doing something like that:</p><pre>git log --oneline | fzf | xargs git revert</pre><p>Just to ensure we’re on the same page, xargs is being used because git revert receives a commit as an argument, and doesn’t take any inputs from standard input, so Xargs will transform the output of fzf into arguments.</p><figure><img alt="git log — oneline | fzf | xargs git revert" src="https://cdn-images-1.medium.com/max/1024/1*Vltd3HsMEyeCtSO42w9WWw.gif" /></figure><p>It didn’t work. That’s because it took the entire line and passed it as arguments. It would be the same as executing the line below:</p><pre>git revert 2b8d302 refactor: separate input_stream from fighter input commands system</pre><p>That is not exacly what we want . What we need is the commit hash (2b8d302) to make the revert. Xargs actually has a way of limiting the maximum number of arguments we want to pass, dropping the rest.</p><pre>git log --oneline | fzf | xargs -n 1 git revert</pre><p>Let’s see what happens now…</p><figure><img alt="git log — oneline | fzf | xargs -n 1 git revert" src="https://cdn-images-1.medium.com/max/1024/1*KlzNWvjoGNxGxuCNZukd_A.gif" /></figure><p>Despite the merge errors that we would need to resolve, it worked like a charm! Xargs got the hash into account and ignored all the rest, avoiding any invalid syntax.</p><h3>Final Thoughts</h3><p>Xargs is awesome! It enables us to write powerful commands by transforming inputs into arguments. That’s the power of automation right there.</p><p>I learned a lot about this subject while writing this article and I hope I managed to pass that knowledge to you, dear reader.</p><p>If any of the information here is wrong or expressed in a confused manner, please let me know.</p><p>I am planning to be much more present on this platform from now on, so I am hoping to see what are your thoughts on these. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcc982fb9969" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Groundbreaking Vim Experience]]></title>
            <link>https://medium.com/@EduardoRodriguesF/the-groundbreaking-vim-experience-88b267dd2f67?source=rss-3c232a2263b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b267dd2f67</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[neovim]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[typing-speed-increase]]></category>
            <dc:creator><![CDATA[Eduardo Rodrigues]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 01:28:59 GMT</pubDate>
            <atom:updated>2023-04-22T01:28:59.859Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A screenshot of my current Neovim setup" src="https://cdn-images-1.medium.com/max/1024/1*iAbD46TdWZrFE2UP3r5j5A.png" /></figure><p>It is April 20th as I am writing this and it has been exactly 300 days since I ditched VS Code for Vim! It was not a time milestone I was actually looking for, but rather a coincidence with the day I feel like showing up to my Medium again.</p><p>I actually didn’t stick with <em>Vim</em>. One month later I moved to <a href="https://neovim.io/">NeoVim</a>, which is basically a more elegant fork of Vim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgsVu8Eaca3Jkg5n43n4MA.png" /><figcaption>The first commits on my nvim configs repository.</figcaption></figure><h3>From the Awkward Mousing to the “<em>Constraint” Keyboard</em></h3><p>Probably most people — myself included — first find it really odd for someone to stop relying on their mouse… Why would you abandon the simplicity of moving your cursor to click, select and drag all you want to having to memorize all those random keystrokes?</p><p>While using VS Code, although I had all those outline visualization, tabs, basic Git operations, nice extensions like <a href="https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens">GitLens</a>; just to name a feel. But I never felt I was managing to do what <em>I want</em>.</p><figure><img alt="Fixing a simple issue in VS Code with keyboard and mouse." src="https://cdn-images-1.medium.com/max/761/1*rnyN5iArBPoGZV-c9tPCpg.gif" /><figcaption>Fixing a simple typo by letting the keyboard go, picking the mouse, selecting the word I wanted to fix and then going back to the keyboard to type again. Very tiring!</figcaption></figure><p>I am sure you got some flashbacks right there too. It happens all the time when you are editing your files. Sure, you could have made it much faster with regular key binds — <strong>Ctrl-ArrowLeft until you reach the word, Ctrl-Shift-ArrowLeft to select your text and start typing again</strong> — but let’s be honest, when you have <em>the option</em> to just use your mouse that is right next to you, that’s going to be your first instinct.</p><p>For me, it felt clunky. I always felt awkward when I did that, and I didn’t knew why because I thought that it simply is what it is… Until it’s not!</p><h4>The Voluntary Restriction</h4><p>When you first startup your Vim session, you will be veeeery slow. You can’t use your mouse, the key bindings are <em>strange</em>, got to keep track of which mode you’re in and what you can do in each of them…</p><p>There is much to learn there yet, so let’s give it a fair shot. Once you understand the semantics of the actions you can take, everything starts feeling natural.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*-HQ81oBwBjsWL-vg-tvHyA.gif" /></figure><p>See what I did there? I jumped to the word I wanted and changed it to another that shows more excitement! For the sake of curiosity, those are the steps it took after typing the whole line:</p><ul><li>&lt;C-[&gt; — Go to NORMAL mode;</li><li>Fb — Find a character (b) before the cursor in the current line;</li><li>ciw — Change inside word (basically erasing it and going into INSERT);</li><li>amazing — What I wanted to type.</li></ul><p>At this point you might argue that this is too much to think about, and I don’t disagree with you. Vim is something you have to <em>want</em> to learn for it to become usable, and this is a great drawback for many people.</p><h3>Learning To Learn</h3><p>I have a couple of personal experiences with learning very specific things out of curiosity, but let’s talk about simple typing. No, I am not talking about no special keyboard layout, or hotkeys. Just typing in a regular QWERTY keyboard.</p><h4>Do It Right, Then Do It Fast</h4><p>Back in 2020, I used to type at 38 words per minute (wpm), which is slightly under the average — 40 wpm. It bothered me a lot. I wanted to type fast… Just for the sake of typing fast.</p><p>With that in mind, I started practicing at <a href="https://www.keybr.com/">keybr.com</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNNbQm3lRlZ_zs0ks7KqeA.png" /><figcaption>My actual account. This is not a sponsor.</figcaption></figure><p>It’s been a while since the last time I did a session, but I tried a quick speed test just to see if I am still in form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIvnH5d20N42z1Et45wtiA.png" /><figcaption>Not bad at all!</figcaption></figure><p>Kind of an improvement for someone who was under the average, right? But it wasn’t as quick as you might think, it actually took me <strong>over 4300 sessions across two months of consistent training.</strong></p><figure><img alt="My progress at keybr.com going from 38 words per minutes to 100." src="https://cdn-images-1.medium.com/max/1024/1*W3wYoTuCxp9CvIHTBRIf5A.png" /></figure><p>And how did I get there? The secret was to do it slowly on purpose.</p><blockquote>But you wanted to go fast! Why go slow on purpose???</blockquote><p>Well, imaginary reader I made up in my head, the section title says it all: <strong>you gotta do it <em>right</em> before doing it <em>fast</em>.</strong></p><p>Analyzing the graph above, you can see my typing speed rapidly increases over the first 500-or-so sessions and then slowly improves over the course of the remaining ~3800 following.</p><p>From the moment I learned to type the <em>right</em> way — carefully positioning my fingers in the keyboard’s home row and using each finger for the appropriate key — I drastically speed up my moves, and than the rest is basically getting confident enough, which <em>then</em> became fast naturally.</p><p>I wouldn’t get anywhere near that if I didn’t watch my steps — I would burn myself out trying to improve upon the wrong practices. But why am I telling you all this when this article is about Vi-like editors?</p><h3>Let’s See What’s That Vim Thing…</h3><h4>Trust the Process and You Won’t Be Let Down</h4><p>When I picked up Vim, I did the same practices. I read a bunch of articles like <a href="https://www.freecodecamp.org/news/vim-beginners-guide/">FreeCodeCamp’s beginner’s guide</a> and had all sorts of <a href="https://vim.rtorr.com/">cheatsheets</a> by my side.</p><p>On the first two weeks, I didn’t have the confidence to integrate it on my job’s workflow. I would just end my shift, pick a random file in my projects folders and start typing random non-sense on a buffer just to get the hang of it.</p><figure><img alt="Doing random movement in a file. Deletions, selections, anything about Vim’s bindings" src="https://cdn-images-1.medium.com/max/1024/1*d9SVgIXnP5HwvV0EFZ4e3w.gif" /></figure><p>This phase was filled with tutorials, plugin experimentation, remaps and all sort of stuff. I was getting to know what I liked about it!</p><h4>Respect the Learning Curve</h4><p>Trying to dive into Vim at once would just overwhelm a person. After those first two weeks I started feeling excited about making it my full-time editor — but I knew it was too early.</p><p>What I did instead was integrating it in my workflow when doing small tweaks in files or so. Changing a version of a package? No problem!</p><figure><img alt="Upgrading a NPM package with Vim." src="https://cdn-images-1.medium.com/max/1024/1*JryzoGAbGIRvZKWvqZSwnw.gif" /></figure><p>For us that already got <a href="https://stackoverflow.com/questions/11828270/how-do-i-exit-vim">stuck on Vim</a> in the past: I embraced those situations and started writing my commit messages this way.</p><figure><img alt="Using git commit without a message flag, so I would enter a Vim session automatically to write a message there." src="https://cdn-images-1.medium.com/max/1024/1*MV8lpSetTOmy4zCYdFeh2A.gif" /></figure><p>Those steps are great at getting you comfortable with Vim’s Mode system.</p><h3>Could There Be Something Better Than Vim?</h3><p>As you might have guessed, Vim did become my main text-editor at the time. VS Code was secondary for when I really needed speed — by that time I still wasn’t getting those speed buffs.</p><p>Vim is a really old text-editor, which is another issue for many people who think about adopting it. I would always get some weird problems on whitespaces. Vim’s syntax highlight implementation is not as up-to-date as it could be too.</p><p>Well, I kinda spoiled that part in the beginning but… Let’s talk about NeoVim!</p><h4>A Much Better Starting Point</h4><p>NeoVim fixed everything wrong with Vim without losing its charm. It has <a href="https://github.com/nvim-treesitter/nvim-treesitter">Treesitter</a> for syntax highlighting, configs and plugins written in Lua, and has a more open-source approach when compared to Vim’s maintenance, which resulted in a much more accelerated overall improvement.</p><h3>The Bloat Versus The Minimal</h3><p>NeoVim has many distros like <a href="https://www.lunarvim.org/">LunarVim</a> or <a href="https://www.lazyvim.org/">LazyVim</a>. For many it is a great starting point, as it aims to feel like a fully-featured IDE or an extension-loaded VS Code.</p><figure><img alt="LunarVim" src="https://cdn-images-1.medium.com/max/1024/0*iBGsZWOg7wJUUlSB.png" /><figcaption>LunarVim workspace example.</figcaption></figure><p>I don’t know if this is a hot take or not, but I think it is a bad idea to start with those. They usually enable mouse out of the box and assign common bindings like &lt;C-s&gt; to save as well. Sounds great in theory, but in the end you are just stuck with old habits again.</p><p>We expect new things to work the way we are used to. This is essentially what these distros try to do for you. This is what most people transitioning from VS Code or IDEs do when setting a NeoVim configuration.</p><p>I am not saying I was free from it. Even though I never liked those fully-featured distros, in my first setting an NeoVim configuration I would put NvimTree on the left while a terminal instance would be fixed at the bottom.</p><p>It didn’t take much longer for me to get rid of both those permanent panels. More recently — after about 6 months into Neovim — it clicked: I wanted to get rid of all the bloat in my screen.</p><h3>Descend Into A Minimalist NeoVim Configuration</h3><p>There are a couple of great reasons to choose a more minimalist approach to your configurations.</p><p>If you look into my <a href="https://github.com/EduardoRodriguesF/nvim/commits/main">Neovim’s configurations Git history</a>, you can observe two things:</p><ol><li>I tweak it a lot;</li><li>I have been removing tons of plugins.</li></ol><p>In 300 days I got to use a huge variation of plugins. <a href="https://github.com/romgrk/barbar.nvim">Barbar</a>, <a href="https://github.com/nvim-tree/nvim-tree.lua">nvim-tree</a>, <a href="https://github.com/numToStr/FTerm.nvim">FTerm</a>, <a href="https://github.com/windwp/nvim-autopairs">nvim-autopairs</a>, are some that make it to the list.</p><p>Even my custom remaps have changed a lot. I used to have jk and kj in Insert mode maps to escape. I also used to like &lt;A-&lt;&gt; and &lt;A-&gt;&gt; to navigate between tabs. I removed it all. But why?</p><h4>Embracing NeoVim as (Vim) is</h4><p>The comfort of replicating already known experiences was preventing me from really getting to know the Vim bindings.</p><p>I’ve been keeping my configurations as close to Vim’s default behavior as possible. Escaping using Esc or &lt;C-[ is reliable. Tabs — when I use them — are fine to navigate with gt and gT.</p><p>All those plugins I mentioned — amazing ones, for the record — got removed as well. Did I really needed to have all my opened buffers in tabs on the top of my screen? Did I really need a pinned file tree?</p><p>We all learned to like those things. But they are useless. For me it only makes sense to avoid those now. I am getting to know Netrw — Vim’s builtin file explorer — and I love it. Tabs became my way to keep track of different workspaces at once.</p><p>Obviously, not everything has to be default. Take a look at <a href="https://github.com/EduardoRodriguesF/nvim/blob/main/after/plugin/packer.lua">my packer file</a>:</p><pre>return require(&#39;packer&#39;).startup(function(use)<br>  -- Packer manages itself<br>  use &#39;wbthomason/packer.nvim&#39;<br><br>  use &#39;nvim-lua/plenary.nvim&#39;<br><br>  use &#39;nvim-lua/popup.nvim&#39;<br>  use &#39;kyazdani42/nvim-web-devicons&#39;<br><br>  -- Indentation markers<br>  use &#39;lukas-reineke/indent-blankline.nvim&#39;<br><br>  -- Git wrapper<br>  use &#39;tpope/vim-fugitive&#39;<br>  -- Git changes on sign column<br>  use &#39;lewis6991/gitsigns.nvim&#39;<br><br>  -- Treesitter language parser<br>  use { &#39;nvim-treesitter/nvim-treesitter&#39;, run = &#39;:TSUpdate&#39; }<br>  -- Shows the context of the currently visible buffer contents<br>  use &#39;nvim-treesitter/nvim-treesitter-context&#39;<br><br>  use &#39;ThePrimeagen/harpoon&#39;<br><br>  -- Undo history tree<br>  use &#39;mbbill/undotree&#39;<br><br>  -- Fuzzy finder<br>  use { &#39;nvim-telescope/telescope.nvim&#39;, tag = &#39;0.1.x&#39; }<br>  use { &#39;nvim-telescope/telescope-fzf-native.nvim&#39;, run = &#39;make&#39; }<br><br>  -- Status line<br>  use &#39;nvim-lualine/lualine.nvim&#39;<br><br>  -- Omni theme<br>  use { &#39;getomni/neovim&#39;, as = &#39;omni&#39; }<br><br>  -- LSP<br>  use {<br>    &#39;VonHeikemen/lsp-zero.nvim&#39;,<br>    branch = &#39;v2.x&#39;,<br>    requires = {<br>      -- LSP Support<br>      { &#39;neovim/nvim-lspconfig&#39; }, -- Required<br>      {<br>        &#39;williamboman/mason.nvim&#39;,<br>        run = function()<br>          pcall(vim.cmd, &#39;MasonUpdate&#39;)<br>        end,<br>      },<br>      { &#39;williamboman/mason-lspconfig.nvim&#39; },<br>      { &#39;jose-elias-alvarez/null-ls.nvim&#39; }, -- For ESLint<br>      { &#39;simrat39/rust-tools.nvim&#39; }, -- For Rust<br>      { &#39;simrat39/symbols-outline.nvim&#39; },<br><br>      -- Autocompletion<br>      { &#39;hrsh7th/nvim-cmp&#39; },<br>      { &#39;hrsh7th/cmp-nvim-lsp&#39; },<br>      { &#39;L3MON4D3/LuaSnip&#39; },<br>    },<br>  }<br>end)</pre><p>I have my fair share of plugins. For navigating between buffers I don’t want to loose, <a href="https://github.com/ThePrimeagen/harpoon">Harpoon</a> is my companion. <a href="https://github.com/nvim-telescope/telescope.nvim">Telescope</a> to find very specific files is amazing. <a href="https://github.com/VonHeikemen/lsp-zero.nvim">LSP Zero</a> concentrates all my language-related plugins in one place.</p><p>Most of them are <em>Add-on</em> plugins. Not replacements to existing Vim functionality. None of them do crazy implementations to the regular Vim workflow. Not even <a href="https://github.com/windwp/nvim-autopairs">autopairs</a> made the cut for me, I’d rather do the pairing myself than allowing plugins to do that for me.</p><p>Another thing I like about my setup is that I keep my NeoVim and Vim settings really close to each other. What I mean is that <a href="https://github.com/EduardoRodriguesF/dotfiles/blob/master/.vimrc">.vimrc</a> is where I actually do my basic settings and remaps for both of them, and simply source it from <a href="https://github.com/EduardoRodriguesF/nvim/blob/main/init.vim">nvim/init.vim</a> file.</p><h4>Why Keep It So Simple?</h4><p>Until now I only showed you my Vim and Neovim setups. I didn’t even have VS Code installed in my personal machine. On my full-time job though, things are a bit different.</p><p>Imagine you are a Junior developer who just got into your first job, and your superior opens up Vim to teach you something. My job requires me to teach concepts and implementations to my coworkers. Often it requires showing them code examples.</p><p>You would miss everything he says until you understand what is happening, because it is confusing for those who are not used to it. For that, I use VS Code.</p><p>But here is the catch: I use <a href="https://marketplace.visualstudio.com/items?itemName=vscodevim.vim">VSCodeVim</a> extension, so I actually can be in the comfort of my Vim bindings. Those extensions are pretty basic implementations of Vim, but they mostly do the job. If I have all crazy remaps in my setup, I would get lost upon going into VS Code.</p><p>I didn’t thought of that initially, so much so that I lost count of how many times I typed jk to exit Insert mode just to realize I didn’t have this binding in here.</p><figure><img alt="Writing in VS Code with Vim extension on, but miss typing a binding that does not exist." src="https://cdn-images-1.medium.com/max/1024/1*skrYJ7MkBV8_v7YZe0fTLw.gif" /><figcaption><em>jk remap is actually awful. Try to write a Dijkstra map implementation with those on…</em></figcaption></figure><p>Many other tools support Vim bindings — <a href="https://obsidian.md/">Obsidian</a> is another great tool with <a href="https://publish.obsidian.md/hub/04+-+Guides%2C+Workflows%2C+%26+Courses/for+Vim+users">that option</a> — , but having to figure out how to do remaps for everything is not something I would like to deal with. The default bindings are great, but each has its own learning curve.</p><h3>A New Way of Thinking</h3><p>I am Brazilian, so English is my second language. Learning Vim feels like learning a new language. At the beginner level you try to associate the meaning of the words of the new language compared to yours.</p><blockquote>So “hello” means “olá”, and “you” means “você”…</blockquote><p>After a lot of lessons, it becomes a separate thing. Instead of being associations in your brain you simply <em>think</em> <em>in that new language</em>. I often learn new words and stuff in English. There will be words that I cannot tell immediately what are their equivalents in Portuguese, simply because it doesn’t matter right away.</p><p>You don’t think about your mouse while writing software anymore. Instead. Relative lines start making sense, and all your desired changes come in mind in semantic keystrokes:</p><ul><li>ci&lt; — Change inside angle brackets (&lt;&gt;);</li><li>va{V — Selecting an entire function;</li><li>f(;di( — Delete all content inside the second () in current line.</li></ul><p>I didn’t memorize all those commands. In fact, I didn’t have to search to write the examples for you. I actually learned what all the components in them mean.</p><p>It is not much different from learning programming. When you get to learn JavaScript, you copy all those complicated words, just to understand what they all do way later.</p><p>After some struggle, it becomes natural. You won’t be searching “How to insert an item in an array.” You’ve done this before, you know how arrays work, and the .push method naturally comes in mind.</p><h3>Final Thoughts</h3><p>I ended up talking more about Vim in general than NeoVim — which I actually use. I just wanted to bring to you the Vim experience as a whole. If you are going to stick with Vim, NeoVim, or even a JetBrains IDE with Vim extension is totally up to you.</p><p>Learning Vim made coding exponentially enjoyable to me. I love figuring out new efficient ways to do things — much like learning new combos in a fighting game. The satisfaction is priceless.</p><p>If you are willing to join the Vim cult, I highly recommend starting by guides like <a href="https://learnvim.irian.to/">Learn Vim The Smart Way</a>. Read, practice, search for more content. It was very worth to me, and I think it just might be for you as well.</p><p>Feel free to see the configurations I use as well:</p><p><a href="https://github.com/EduardoRodriguesF/nvim">GitHub - EduardoRodriguesF/nvim: Minimal Neovim configuration</a></p><p>Thanks for passing by, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b267dd2f67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing Rust Games in WSL]]></title>
            <link>https://medium.com/better-programming/developing-rust-games-in-wsl-677cd1f37bc1?source=rss-3c232a2263b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/677cd1f37bc1</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[bevy]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Eduardo Rodrigues]]></dc:creator>
            <pubDate>Fri, 18 Nov 2022 00:50:56 GMT</pubDate>
            <atom:updated>2023-04-27T15:11:24.648Z</atom:updated>
            <content:encoded><![CDATA[<h4>Running your games in native Windows while working from WSL</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DGUlXwy_wVrmYqro" /><figcaption>Photo by <a href="https://unsplash.com/@alexxsvch?utm_source=medium&amp;utm_medium=referral">Alexey Savchenko</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Game development is a hobby I try to work on from time to time, and recently I have been learning to code in Rust, so I thought it would be interesting to see how it goes with game programming, and it’s great! However, I noticed problems I couldn’t find much content online about, so I’m doing it in case you ever find yourself in that same situation.</p><p>Just like most programmers, I love using Linux to get my work done. Yet GUIs like Ubuntu or Manjaro never really suited me, there is something about Windows usability that I simply cannot let go of, so naturally I quickly fell in love with the Windows Subsystem for Linux (WSL), which combines the Windows graphical interface while I can use a great Linux terminal.</p><h3>My Setup</h3><p>I work using a Windows 11 system with WSL2 configured with <a href="https://github.com/yuk7/ArchWSL">ArchWSL</a>, a non-official ArchLinux system for WSL based on wsldl. My favorite text editor is Neovim, so I never get out of my terminal.</p><p>Basically, all my work is done inside this subsystem, while for browsing the web and using any graphical interface I prefer to use my regular Windows.</p><h3>The Problem</h3><p>I initially picked <a href="https://hands-on-rust.com/">Hands-on Rust</a> just to get a grasp of what game programming with Rust looks like. After finishing reading, I searched for other engines and soon enough <a href="https://bevyengine.org/">Bevy Engine</a> caught my attention. It is still in early development, so it has many feature gaps, but what is available for now is enough to show how powerful this engine is and will be.</p><p>Excited, I got some material and started learning to use it, and in case you did it as well, you may have found yourself with that boilerplate code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d38a78586201446197e9ca7ee75fbc0e/href">https://medium.com/media/d38a78586201446197e9ca7ee75fbc0e/href</a></iframe><p>This is the most basic Bevy app that opens a blank window, but trying to run it from WSL would result in the following error:</p><figure><img alt="“Unable to find GPU” error message" src="https://cdn-images-1.medium.com/max/1024/1*MfQ9xizVM97jI4e85Sy7bQ.png" /></figure><p>Unable to find a GPU?! How come??? Well, it turns out Bevy currently only supports Vulkan as its graphics API. I did a lot of research about this topic, but there is no viable way to run Vulkan from WSL, although the issue is already tracked <a href="https://github.com/microsoft/wslg/issues/40">here</a>.</p><p>Using Powershell would be the simplest way to keep doing my stuff, but I didn’t want to leave my terminal and my Neovim behind for that, so I needed to think of a workaround.</p><h3>The Solution</h3><p>Thankfully, there is a way to access the native Windows Powershell from inside WSL, with the syntax below:</p><pre>$ powershell.exe -Command &quot;&lt;command&gt;&quot;</pre><p>Well, that is great! All I have to do is run cargo from there.</p><pre>$ powershell.exe -Command &quot;cargo run&quot;</pre><p>BAM! Problem solved! Let’s get back to…</p><figure><img alt="“Unable to find GPU” error." src="https://cdn-images-1.medium.com/max/1024/1*jm_a4sPIfCmo6MZILZ_lfg.png" /><figcaption>Sadness in a picture.</figcaption></figure><p>Okay, almost there. Powershell has some trouble resolving executable paths that are inside the subsystem. To fix that is quite simple actually, we just need to find a way to copy our game to Windows and then cargo run from there.</p><p>To copy the directory, I chose to use rsync. Why, would you ask? Copying using cp would bring all temporary files with us, like the target folder, unless we hack together a bash script to ignore those files. There is no need for that, because rsync has an — exclude-from flag, that allows you to specify a file with file patterns to ignore.</p><p>Install rsync using your system’s package manager:</p><pre># ArchLinux<br>$ sudo pacman -S rsync<br><br># Ubuntu<br>$ sudo apt-get install rsync</pre><p>What better file to set as our pattern of files to <em>ignore</em> than .gitignore? We just need to define a directory on Windows to keep our game file. For that, I decided on C:\Windows\temp, which is the directory for temporary files that Windows generate by itself.</p><p>So, after defining those details, we could run the following commands to quickly copy our game source code to a Windows environment:</p><pre>$ mkdir /mnt/c/Windows/temp/my-cool-game -p<br><br>$ rsync . /mnt/c/Windows/temp/my-cool-game -r --exclude-from=.gitignore</pre><p>The first line creates our game temporary directory, and we use the -p flag so it does not generate an error if the directory already exists — this is going to be useful later on.</p><p>The second and last line is our rsync command described! This generates a fresh copy of our source code in a matter of seconds, ignoring all junk files. Also notice that the temp path starts with /mnt/, which is the way to tell WSL that we want to access our Windows file system.</p><p>Now, if we cd to this directory and run Powershell from there…</p><pre>$ cd /mnt/c/Windows/temp/my-cool-game<br><br>$ powershell.exe -Command &quot;cargo run&quot;</pre><p>Our game window would start up from Windows!</p><figure><img alt="Empty window" src="https://cdn-images-1.medium.com/max/1024/1*GJJj4OKvDh0VJMfvTcqeCQ.png" /></figure><p>Obviously, it’s blank, since we just have boilerplate code to run the program.</p><p>However, by doing that, we have a solution to run and play our game while working from WSL, though it’s a slow and boring process. So let’s automate it!</p><p>We want something totally reusable that we can copy around to any new project without worrying too much about it. Create run.sh with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c5f85fa48e4b952972e5c536af8d3ce/href">https://medium.com/media/8c5f85fa48e4b952972e5c536af8d3ce/href</a></iframe><p>Let’s break that code down so you don’t have to guess what each line does.</p><ul><li>Line 3 — Variable to store the directory name, so we can later create a temporary directory with the same name automatically;</li><li>Line 4 — Variable to store the absolute path to the temporary directory. Notice that it uses our previously created directory_name variable;</li><li>Line 6 — Creates the directory using -p, so it doesn’t error in case it already exists;</li><li>Line 8 — Copies the contents of our directory to the temporary one, like we previously did;</li><li>Line 10 — Changes to a temporary directory. It won’t affect us directly, since bash scripts run in a child process;</li><li>Line 12 and last — Runs cargo.</li></ul><p>Notice that, in our Powershell line, we pass $@ as an argument to run. This is a default Linux Shell variable that passes down every argument we pass while executing the script.</p><p>To make it executable, it’s important to change its mode with chmod +x run.sh. Now we can simply run ./run.sh and everything will be taken cared of for us automatically.</p><p>It would be simple enough to change it into a build.sh, or even a generic cargo.sh to run any command from cargo CLI.</p><pre>powershell.exe -Command &quot;cargo $@&quot;</pre><p>The way you’d handle each command comes down to your own preference.</p><h3>Happy hacking!</h3><p>This article might get obsolete as soon as Bevy starts to support OpenGL, or even when WSL itself supports Vulkan, but since most of your players use Windows, I would still find it useful to test in your audience’s language, while also being able to code from WSL for a better developer experience.</p><p>Thank you, a lot, for reaching out here! This is actually my first article and I plan to show up with more things I like talking about or solutions like this one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=677cd1f37bc1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/developing-rust-games-in-wsl-677cd1f37bc1">Developing Rust Games in WSL</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>