<?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 Nirmal Perera on Medium]]></title>
        <description><![CDATA[Stories by Nirmal Perera on Medium]]></description>
        <link>https://medium.com/@nirmalperera2509?source=rss-40963a346e5c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cfkgdnYPopxeA-KxprsINw.jpeg</url>
            <title>Stories by Nirmal Perera on Medium</title>
            <link>https://medium.com/@nirmalperera2509?source=rss-40963a346e5c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:21:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nirmalperera2509/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[When HTTP 200 Turns Into 404: A Reactive Programming Bug I Didn’t Expect in Spring WebFlux]]></title>
            <link>https://medium.com/@nirmalperera2509/when-http-200-turns-into-404-a-reactive-programming-bug-i-didnt-expect-in-spring-webflux-112fb0596ccf?source=rss-40963a346e5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/112fb0596ccf</guid>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Nirmal Perera]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 01:23:21 GMT</pubDate>
            <atom:updated>2026-11-25T01:23:21.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kiNopxqEYd0B5IU4C4VqIw.png" /></figure><p>Recently, I’ve been working on a personal project called <strong>GateFlow</strong>.</p><p>GateFlow is an API management and gateway platform that I’m building using Spring Boot, Spring Cloud Gateway WebFlux, PostgreSQL, and Redis.</p><p>The idea is relatively simple.</p><p>Imagine you’re building an application that needs to consume an external API. Instead of directly connecting to that API, you register it in GateFlow. Your application gets an API key, and all requests go through the GateFlow Gateway.</p><p>The Gateway takes care of API key validation, subscription verification, and request forwarding.</p><p>Something like this:</p><pre>Client Application<br>       |<br>       | X-API-Key<br>       v<br>GateFlow Gateway<br>       |<br>       | Validate API Key<br>       | Check Subscription<br>       | Resolve API<br>       |<br>       v<br>External API</pre><p>I had already implemented API key generation, validation, database lookups, and subscription management.</p><p>Everything seemed to be working fine.</p><p>Until I decided to test an actual external API.</p><h3>The plan: Let’s connect a real API</h3><p>I didn’t want to test everything using dummy endpoints, so I decided to use the public Dog CEO API.</p><p>For this experiment, I selected the following endpoint:</p><p><a href="https://dog.ceo/api/breed/hound/list">https://dog.ceo/api/breed/hound/list</a></p><p>It returns a list of sub-breeds belonging to the hound breed.</p><p>I registered it in GateFlow with the following configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*TpQ2q1_IEYExDIoEncmFJw.png" /></figure><p>I also created an application, subscribed it to the registered API, and generated a TEST API key.</p><p>The expected request from my client was:</p><pre>GET http://localhost:8082/gateway/dog-breeds/v1/list<br>X-API-Key: YOUR_GATEFLOW_API_KEY</pre><p>The Gateway was supposed to:</p><ol><li>Validate the API key.</li><li>Identify the application associated with that key.</li><li>Check whether the application had an active subscription.</li><li>Resolve the registered API using its slug and version.</li><li>Retrieve the upstream URL from PostgreSQL.</li><li>Forward the request to the external API.</li></ol><p>Everything was ready.<br>I sent the request.<br>And got a 404.</p><h3>The debugging journey</h3><p>My first thought was that something was wrong with the API registration.</p><p>Maybe I had entered the wrong slug. Maybe the subscription wasn’t active. Maybe the application ID wasn’t being resolved correctly.</p><p>So, instead of immediately changing the code, I started checking things one by one.</p><h3>First, I checked the API key</h3><p>I sent a request without an API key.</p><p>The Gateway correctly returned:</p><pre>401 Unauthorized</pre><p>That meant my API key authentication filter was actually running.</p><h3>Next, I checked the database</h3><p>I queried PostgreSQL to verify the API key, application, subscription, and registered API.</p><p>Everything looked correct</p><p>The API key was ACTIVE.</p><p>The subscription was ACTIVE.</p><p>The API was ACTIVE.</p><p>The slug was dog-breeds.</p><p>The version was v1.</p><p>I then executed the exact SQL query used by my Gateway’s ApiRouteRepository.</p><p>It returned the expected API record.</p><p>So, the database wasn’t the problem.</p><h3>Then I added some debugging logs</h3><p>I wanted to see what was actually happening inside the route resolution service.</p><p>I temporarily added a few System.out.println() statements.</p><p>This was the output:</p><pre>Application ID:<br>06d17f35-2b2a-419b-bc27-71ae97c335b9</pre><pre>API Slug: dog-breeds<br>API Version: v1</pre><pre>API FOUND:<br>ApiRouteRecord[<br>    apiId=30458c73-0e28-4fda-a910-65c3160e2ef5,<br>    organizationId=abf31c63-51e6-42f4-bb83-3c5ad2574df7,<br>    slug=dog-breeds,<br>    version=v1,<br>    baseUrl=https://dog.ceo/api/breed/hound<br>]</pre><p>Now I knew something important.</p><p>The Gateway was successfully:</p><ul><li>Validating the API key.</li><li>Identifying the application.</li><li>Resolving the API.</li><li>Finding the correct upstream URL.</li></ul><p>But the client was still receiving a 404.</p><p>I started suspecting that the problem was somewhere in the forwarding process.</p><h3>The surprising discovery</h3><p>I added another debugging statement around the forwarding operation.</p><p>My forwarding method looked something like this:</p><pre>private Mono&lt;Void&gt; forward(<br>        ServerWebExchange exchange,<br>        GatewayFilterChain chain,<br>        ApiRouteRecord apiRoute,<br>        String remainingPath<br>) {<br>    // Build the upstream URL<br>    <br>    // Mutate the request<br>    <br>    // Set the destination URL<br>   <br>    return chain.filter(mutatedExchange);<br>}</pre><p>For anyone unfamiliar with Spring Cloud Gateway, chain.filter() passes the request to the next filter in the Gateway processing chain.</p><p>It returns a Mono&lt;Void&gt;.</p><p>I added a log to check what happened after the forwarding operation completed.</p><p>And this was the result:</p><pre><br>Upstream URL: https://dog.ceo/api/breed/hound/list<br>Response status: 200 OK</pre><p>Wait a minute.</p><p>The external API was returning 200 OK.</p><p>The forwarding operation was completing successfully.</p><p>But my client was still receiving:</p><pre>404 Not Found</pre><p>At this point, I knew the problem wasn’t the database, API key, subscription, or external API.</p><p>It was something in my reactive pipeline.</p><h3>Understanding the actual problem</h3><p>This is where I learned something important about Project Reactor.</p><p>If you’ve worked with Spring WebFlux, you’ve probably encountered Mono and Flux.</p><p>But I hadn’t fully understood one particular detail about Mono&lt;Void&gt;.</p><p>Let’s break it down.</p><h3>What exactly is Mono?</h3><p>In Project Reactor, Mono&lt;T&gt; represents an asynchronous operation that can produce zero or one value.</p><p>For example:</p><pre>Mono&lt;String&gt; message = Mono.just(&quot;Hello World&quot;);</pre><p>This produces one value:</p><pre>Hello World</pre><p>We can also have:</p><pre>Mono&lt;String&gt; message = Mono.empty();</pre><p>This completes successfully without producing any value.</p><p>Now, what about Mono&lt;Void&gt;?</p><p>It’s commonly used when an operation doesn’t need to return a value, but we still need to know when it completes.</p><p>For example:</p><pre>Mono&lt;Void&gt; result = someOperation();</pre><p>Think of it as:</p><p>“I don’t need a value from this operation. I just need to know when it finishes.”</p><p>This is exactly what happens with Spring Cloud Gateway’s chain.filter().</p><pre>return chain.filter(mutatedExchange);</pre><p>The request gets processed, the external API responds, and the operation completes.</p><p>But the returned publisher doesn’t emit a value.</p><p>That’s the important part.</p><p><strong>Successful completion doesn’t necessarily mean that a value was emitted.</strong></p><h3>So, where did I go wrong?</h3><p>Here was my original implementation:</p><pre>return routeResolutionService.resolve(<br>        apiKey.applicationId(),<br>        slug,<br>        version<br>).flatMap(apiRoute -&gt;<br>        forward(exchange, chain, apiRoute, remainingPath)<br>).switchIfEmpty(Mono.defer(() -&gt; writeError(<br>        exchange,<br>        HttpStatus.NOT_FOUND,<br>        &quot;API not found or not accessible&quot;<br>)));</pre><p>At first glance, this looked perfectly reasonable.</p><p>My intention was:</p><ul><li>If the API exists, forward the request.</li><li>If the API doesn’t exist, return 404.</li></ul><p>But let’s look at what actually happens.</p><p>routeResolutionService.resolve() returns a Mono&lt;ApiRouteRecord&gt;.</p><p>When the API is found, flatMap() executes the forwarding operation.</p><p>However, forward() returns Mono&lt;Void&gt;.</p><p>When that operation completes successfully, it doesn’t emit a value.</p><p>Consequently, the resulting publisher completes empty.</p><p>And then comes the problem:</p><pre>.switchIfEmpty(...)</pre><p>This operator doesn’t know why the publisher completed without emitting a value.</p><p>It simply sees an empty completion and switches to the alternative publisher.</p><p>So even though the API was found and the external request succeeded, my 404 handler was executed.</p><p>That was the bug.</p><h3>The fix: thenReturn() and defaultIfEmpty()</h3><p>I needed to distinguish between two different situations:</p><ol><li>The API wasn’t found.</li><li>The API was found and the forwarding operation completed successfully.</li></ol><p>The solution was to emit a value after successful forwarding.</p><p>I changed the implementation to:</p><pre>return routeResolutionService.resolve(<br>        apiKey.applicationId(),<br>        slug,<br>        version<br>).flatMap(apiRoute -&gt;<br>        forward(exchange, chain, apiRoute, remainingPath)<br>                .thenReturn(true)<br>).defaultIfEmpty(false)<br> .flatMap(found -&gt; {<br>     if (found) {<br>         return Mono.empty();<br>     }<br>     return writeError(<br>                  exchange,<br>                  HttpStatus.NOT_FOUND,<br>                  &quot;API not found or not accessible&quot;<br>          );<br>      });</pre><p>Let’s understand the two important operators.</p><h3>1. thenReturn(true)</h3><pre>forward(exchange, chain, apiRoute, remainingPath)<br>        .thenReturn(true)</pre><p>thenReturn() waits for the previous publisher to complete successfully and then emits the specified value.</p><p>In our case:</p><ul><li>Forwarding completes successfully.</li><li>thenReturn(true) emits true.</li></ul><p>If forwarding fails with an error, the error is propagated instead. It doesn’t emit true.</p><h3>2. defaultIfEmpty(false)</h3><pre>.defaultIfEmpty(false)</pre><p>This provides a default value when the previous publisher completes without emitting anything.</p><p>So now:</p><ul><li>API found and forwarding succeeds → true.</li><li>API not found → false.</li></ul><p>We can then handle those cases separately.</p><p>If the value is true, the request has already been forwarded, so we simply complete the filter.</p><p>If the value is false, we return our custom 404 response.</p><p>The key difference is that we no longer use the empty completion of Mono&lt;Void&gt; to determine whether the database lookup succeeded.</p><h3>Finally, the result!</h3><p>After applying the fix, I restarted the Gateway and sent the same request again.</p><pre>GET http://localhost:8082/gateway/dog-breeds/v1/list<br>(header) X-API-Key: &lt;Generated API Key&gt;</pre><p>And finally:</p><pre>200 OK</pre><p>The response:</p><pre>{<br>    &quot;message&quot;: [<br>        &quot;afghan&quot;,<br>        &quot;basset&quot;,<br>        &quot;blood&quot;,<br>        &quot;english&quot;,<br>        &quot;ibizan&quot;,<br>        &quot;plott&quot;,<br>        &quot;walker&quot;<br>    ],<br>    &quot;status&quot;: &quot;success&quot;<br>}</pre><p>My first successful external API request through GateFlow!</p><h3>What I learned from this</h3><p>This debugging session taught me a few things that I probably wouldn’t have understood by simply reading the documentation.</p><p><strong>1. An HTTP response and a reactive publisher are two different things.</strong></p><p>An HTTP request can complete successfully with a 200 response, while the corresponding Mono&lt;Void&gt; completes without emitting a value.</p><p><strong>2. </strong><strong>switchIfEmpty() needs to be used carefully.</strong></p><p>It reacts to an empty publisher, not necessarily to a failed operation or a missing database record.</p><p><strong>3. Debugging the entire request lifecycle matters.</strong></p><p>Instead of randomly changing the database or authentication logic, I added logs at different stages until I found exactly where things went wrong.</p><p><strong>4. Understanding the operators is more important than memorizing them.</strong></p><p>I could have copied a solution from somewhere, but understanding why thenReturn() fixed the problem gave me a much better understanding of reactive programming.</p><p>I’m still building GateFlow, and there are plenty of things left to implement, including rate limiting, quota enforcement, usage tracking, and additional security controls.</p><p>But this was one of those small debugging experiences that taught me something worth remembering.</p><p>Sometimes, the most confusing bugs aren’t caused by complicated business logic.</p><p>Sometimes, it’s just one empty Mono&lt;Void&gt; in the wrong place.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=112fb0596ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built an NPM Library to Standardize University Group Projects (and Learned the Hard Way)]]></title>
            <link>https://medium.com/@nirmalperera2509/how-i-built-an-npm-library-to-standardize-university-group-projects-and-learned-the-hard-way-65fc4ebadfbe?source=rss-40963a346e5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/65fc4ebadfbe</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[npm-private-registry]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Nirmal Perera]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 18:46:28 GMT</pubDate>
            <atom:updated>2026-03-24T18:46:28.574Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A journey from chaotic codebases to streamlined collaboration — complete with mistakes, bans, and lessons learned</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjTtVOH-Qaj4_gudla7UoA.webp" /></figure><p>If you’ve ever worked on a group project at university, you know the pain. Teammates implement the same functionality differently, response formats are inconsistent, validations are missing, and authentication logic is scattered everywhere.</p><p>I decided to fix this by creating a personal NPM library to centralize common functionality — response formats, validation, authentication, and TypeScript types. The result? My team now has a single source of truth.</p><p>Here’s how I did it, what went wrong, and what I learned.</p><h3>The Problem</h3><p>Every project had the same issues:</p><ul><li><strong>Inconsistent response formats</strong> — Some returned { message, data }, others { succes, response {data}, message }</li><li><strong>Validation chaos</strong> — Some endpoints validated input, others just hoped for the best</li><li><strong>Authentication anarchy</strong> — JWT verification implemented differently in every service</li><li><strong>Endless reimplementation</strong> — Common functions rewritten in each project</li></ul><p>We needed a reusable solution that made consistency the default.</p><h3>The Solution</h3><p>I created an NPM library containing TypeScript types, validation helpers, authentication middleware, and utility functions. Teammates simply import the library instead of reimplementing common code.</p><h3>The Publishing Journey (My Mistakes)</h3><p><strong>Attempt #1:</strong> I accidentally published both the src and dist folders. This was a mistake because the src folder exposes raw implementations that users shouldn’t depend on directly—only the compiled dist should be published.</p><p><strong>The Fix:</strong> I unpublished the package, updated package.json to point only to dist, created a .npmignore to exclude unnecessary files, and rebuilt the project properly.</p><p><strong>Attempt #2:</strong> I tried republishing immediately and got a 24-hour ban. NPM enforces strict rules to prevent spam — too many unpublish/republish cycles trigger automatic restrictions.</p><h3>Essential NPM Commands (and What They Do)</h3><p>Here are the commands that saved me:</p><p><strong>Testing &amp; Development</strong></p><pre># Link library locally for testing<br>npm link</pre><pre># Test what will be published<br>npm pack<br>tar -tzf *.tgz</pre><p><strong>Publishing</strong></p><pre># Check you&#39;re logged in as correct user<br>npm whoami</pre><pre># Publish a public package<br>npm publish --access private # anyone can install</pre><pre># Publish a private package (with scope)<br># Requires a paid npm plan<br>npm publish --access restricted   # for scoped private packages</pre><pre># Bump version before publishing<br>npm version patch   # or minor/major depending on the change</pre><p><strong>Version Management</strong></p><pre># Remove a version (within 72 hours)<br>npm unpublish package@version</pre><pre># Force remove (use carefully)<br>npm unpublish package@version --force</pre><pre># Deprecate instead (preferred)<br>npm deprecate package@version &quot;Use 1.0.1 instead&quot;</pre><p><strong>My Publishing Workflow:</strong></p><pre>npm run build<br>npm pack &amp;&amp; tar -tzf *.tgz  # Verify contents<br>npm version patch<br>npm publish --access public<br>git push --follow-tags</pre><h3>Lessons Learned</h3><ul><li><strong>Always publish compiled code</strong> — never the src folder</li><li><strong>Use </strong><strong>.npmignore effectively</strong> — exclude tests, configs, source files</li><li><strong>Test locally with </strong><strong>npm link</strong> before publishing</li><li><strong>Follow semantic versioning</strong> — your users depend on it</li><li><strong>NPM is strict for good reasons</strong> — too many unpublish cycles trigger bans</li><li><strong>Centralized libraries save massive time</strong> — the upfront investment pays off fast</li></ul><h3>The Impact</h3><p>(To be updated later)</p><h3>Final Thoughts</h3><p>Creating a personal NPM library might seem like overkill for a university project — but the payoff is enormous. It saved hours of repetitive work and taught me best practices in TypeScript, package publishing, and team collaboration.</p><p>If you’re tired of rewriting the same code or fixing inconsistent implementations, consider building a shared library. A small upfront investment pays off massively in efficiency and maintainability.</p><p>And remember: every mistake is a lesson, every ban is a learning opportunity, and every successful publish is a step toward better engineering.</p><p><em>Have you built your own NPM library? Share your experiences in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65fc4ebadfbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jenkins Explained: From Installation to Pipelines, Automation, and Security]]></title>
            <link>https://medium.com/@nirmalperera2509/jenkins-explained-from-installation-to-pipelines-automation-and-security-9eec94dcd68d?source=rss-40963a346e5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eec94dcd68d</guid>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Nirmal Perera]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 17:26:24 GMT</pubDate>
            <atom:updated>2026-03-10T17:32:21.601Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*fiOou8ZYaZe-Ka8NUyovMw.png" /></figure><p>Modern software teams rely heavily on <strong>automation</strong> to ship reliable software faster. One of the most widely used tools for this is <strong>Jenkins</strong>, an open-source automation server designed to support <strong>Continuous Integration (CI)</strong> and <strong>Continuous Delivery (CD)</strong>.</p><p>This article walks through the core concepts of Jenkins — from architecture and installation to pipelines, automation, and security practices.</p><h3>What is Jenkins?</h3><p>Jenkins is an <strong>open-source automation server</strong> used to automate the building, testing, and deployment of applications.</p><p>In a typical CI/CD workflow:</p><pre>Developer pushes code → Version Control System (Git)<br>                       → Jenkins detects the change<br>                       → Jenkins pulls the code<br>                       → Jenkins executes tasks defined in Jenkinsfile</pre><p>These tasks may include:</p><ul><li>Compiling code</li><li>Running automated tests</li><li>Packaging applications</li><li>Deploying to environments</li></ul><h3>Core Jenkins Concepts</h3><h3>Jobs</h3><p>A <strong>job</strong> defines a specific task Jenkins should perform.</p><p>Examples:</p><ul><li>Compile code</li><li>Run unit tests</li><li>Deploy an application</li></ul><h3>Builds</h3><p>A <strong>build</strong> is a single execution of a job.</p><p>Jenkins maintains a <strong>history of builds</strong>, which is useful for:</p><ul><li>Debugging failures</li><li>Tracking changes</li><li>Monitoring performance</li></ul><h3>Freestyle Projects</h3><p>The <strong>Freestyle Project</strong> is Jenkins’ simplest project type.</p><p>It allows users to define custom tasks through the Jenkins UI without writing pipeline code.</p><p>However, freestyle projects have limitations:</p><ul><li>Limited workflow control</li><li>Configuration stored in UI instead of code</li><li>Difficult to manage complex pipelines</li><li>Cannot resume builds after failure</li></ul><p>Because of this, most modern teams prefer <strong>pipeline-based builds</strong>.</p><h3>Jenkins Architecture</h3><p>Jenkins uses a <strong>distributed architecture</strong> consisting of:</p><ul><li>Controller (Master)</li><li>Worker Nodes (Agents)</li></ul><h3>Jenkins Controller</h3><p>The <strong>controller</strong> is the central server that manages the entire CI/CD system.</p><p>It contains:</p><ul><li>Jobs</li><li>Plugins</li><li>Nodes</li><li>Credentials</li><li>System configuration</li></ul><p>Responsibilities include:</p><p><strong>1. User management</strong></p><ul><li>Authentication</li><li>Access control</li></ul><p><strong>2. Pipeline orchestration</strong></p><ul><li>Defining pipelines</li><li>Scheduling builds</li><li>Monitoring executions</li></ul><p><strong>3. Web interface</strong></p><ul><li>Jenkins dashboard</li><li>Build history</li><li>Configuration management</li></ul><p>Think of the controller as the <strong>brain of the Jenkins system</strong>.</p><h3>Worker Nodes (Agents)</h3><p>Worker nodes execute the actual build tasks.</p><p>They connect to the controller using:</p><ul><li><strong>SSH (Secure Shell)</strong></li><li><strong>JNLP (Java Network Launch Protocol)</strong></li></ul><p>Each worker node has a configurable number of <strong>executors</strong>.</p><h3>Executors</h3><p>An executor is a <strong>thread responsible for executing a task</strong>.</p><p>More executors allow multiple jobs to run simultaneously.</p><p>A good rule of thumb:</p><ul><li>1 executor per CPU core for small workloads.</li></ul><p>Executor allocation should consider:</p><ul><li>CPU</li><li>Memory</li><li>Disk resources</li></ul><h3>Deployment Models</h3><h3>Basic Deployment</h3><pre>Controller + Worker on the same machine</pre><p>Simple and suitable for small teams or experimentation.</p><h3>Advanced Deployment</h3><pre>Controller node<br>      |<br>      |---- Worker Node<br>      |---- Worker Node<br>      |---- Worker Node</pre><p>Advantages:</p><ul><li>Prevents controller overload</li><li>Isolates build environments</li><li>Improves performance through parallel builds</li><li>Supports horizontal scaling</li></ul><h3>Installing Jenkins (Ubuntu Example)</h3><p>Jenkins requires <strong>Java</strong> to run.</p><p>Install Java first:</p><pre>sudo apt update<br>sudo apt install fontconfig openjdk-21-jre</pre><p>Add the Jenkins repository:</p><pre>sudo wget -O /etc/apt/keyrings/jenkins-keyring.asc \<br>https://pkg.jenkins.io/debian-stable/jenkins.io.key</pre><p>Add repository to sources list:</p><pre>echo &quot;deb [signed-by=/etc/apt/keyrings/jenkins-keyring.asc]&quot; \<br>https://pkg.jenkins.io/debian-stable binary/ | sudo tee \<br>/etc/apt/sources.list.d/jenkins.list</pre><p>Install Jenkins:</p><pre>sudo apt update<br>sudo apt install jenkins</pre><p>Check service status:</p><pre>systemctl status jenkins</pre><p>View logs:</p><pre>journalctl -u jenkins</pre><p>Restart Jenkins if needed:</p><pre>systemctl restart jenkins</pre><h3>Types of Jenkins Projects</h3><p>Jenkins supports multiple project types.</p><h3>1. Freestyle Project</h3><p>Flexible job definitions through the UI.</p><p>Best for:</p><ul><li>Small tasks</li><li>Quick experiments</li></ul><h3>2. Pipeline Project</h3><p>Defines CI/CD pipelines using <strong>code</strong>.</p><p>Supports:</p><ul><li>Stages</li><li>Conditions</li><li>Complex workflows</li></ul><h3>3. Multibranch Pipeline</h3><p>Automatically builds <strong>multiple branches</strong> of a repository.</p><p>Useful for:</p><ul><li>Feature branches</li><li>Large development teams</li></ul><h3>4. Maven Project</h3><p>Designed for projects built using <strong>Apache Maven</strong>.</p><h3>5. Multi-Configuration Project</h3><p>Runs builds across multiple configurations such as:</p><ul><li>Different OS versions</li><li>Multiple JDK versions</li></ul><h3>6. Organization Folders</h3><p>Helps organize Jenkins projects in <strong>hierarchical folders</strong>.</p><h3>Extending Jenkins with Plugins</h3><p>Jenkins is highly extensible through plugins.</p><p>Plugins are distributed as:</p><pre>.hpi  (Hudson plugin format)<br>.jpi  (Jenkins plugin format)</pre><p>If both exist, .jpi takes priority.</p><p>Plugins may contain:</p><ul><li>Code</li><li>Resources</li><li>Configuration files</li></ul><p>Example plugins:</p><p><strong>Copy Artifact Plugin</strong></p><p>Allows sharing files produced by one job with other jobs.</p><p><strong>Yet Another Build Visualizer</strong></p><p>Visualizes upstream and downstream build relationships.</p><h3>Jenkins Fingerprints</h3><p>Jenkins fingerprints track how files move between builds and jobs.</p><p>They help answer questions like:</p><ul><li>Which build produced this artifact?</li><li>Which downstream job consumed it?</li></ul><p>Fingerprints store:</p><ul><li>File checksum</li><li>Job usage information</li></ul><p>These records are stored inside:</p><pre>$JENKINS_HOME/fingerprints</pre><p>This feature is extremely useful for <strong>large interconnected pipelines</strong>.</p><h3>Jenkins Pipelines</h3><p>Pipelines define CI/CD workflows using code.</p><p>Example pipeline:</p><pre>pipeline {<br>    agent any   <br>    stages {<br>        stage(&#39;Build&#39;) {<br>            steps {<br>                sh &#39;mvn clean package&#39;<br>            }<br>         }<br>         stage(&#39;Unit Test&#39;) {<br>            steps {<br>                junit &#39;target/surefire-reports/*.xml&#39;<br>            }<br>        }<br>        stage(&#39;Deploy&#39;) {<br>            when {<br>                branch &#39;main&#39;<br>            }<br>            steps {<br>                sh &#39;./deploy.sh&#39;<br>            }<br>        }<br>    }<br>}</pre><p>This pipeline:</p><ol><li>Builds the application</li><li>Runs tests</li><li>Deploys only if the branch is main</li></ol><h3>Important Jenkinsfile Directives</h3><h3>Environment</h3><p>Defines environment variables for the pipeline.</p><pre>environment {<br>    APP_ENV = &quot;production&quot;<br>}</pre><h3>Post</h3><p>Runs actions after pipeline execution.</p><p>Common uses:</p><ul><li>Notifications</li><li>Cleanup</li></ul><pre>post {<br>    success {<br>        echo &quot;Build succeeded&quot;<br>    }<br>    failure {<br>        echo &quot;Build failed&quot;<br>    }<br>}</pre><h3>Script</h3><p>Allows execution of Groovy logic inside pipelines.</p><pre>script {<br>    def files = [&#39;file1.txt&#39;, &#39;file2.txt&#39;]<br>    files.each { file -&gt;<br>        sh &quot;echo Processing ${file}&quot;<br>    }<br>}</pre><h3>When</h3><p>Controls whether a stage should run.</p><pre>when {<br>    branch &#39;main&#39;<br>}</pre><h3>Credentials</h3><p>Access secrets stored securely in Jenkins.</p><pre>withCredentials([string(credentialsId: &#39;api-key&#39;, variable: &#39;API_KEY&#39;)]) {<br>    sh &#39;echo Using secure credentials&#39;<br>}</pre><h3>Input</h3><p>Allows manual approval during pipeline execution.</p><pre>input {<br>    message &quot;Deploy to production?&quot;<br>}</pre><h3>Parameters</h3><p>Creates configurable builds.</p><pre>parameters {<br>    string(name: &#39;ENV&#39;, defaultValue: &#39;dev&#39;)<br>}</pre><h3>Stash / Unstash</h3><p>Stores artifacts between stages.</p><pre>stash name: &#39;build-artifacts&#39;<br>unstash name: &#39;build-artifacts&#39;</pre><h3>Parallel Stages</h3><p>Runs independent stages simultaneously.</p><pre>parallel {<br>    stage(&#39;Unit Tests&#39;) { ... }<br>    stage(&#39;Security Scan&#39;) { ... }<br>}</pre><p>This significantly <strong>reduces pipeline execution time</strong>.</p><h3>Automating Jenkins</h3><p>Jenkins supports automation through:</p><ol><li><strong>Jenkins CLI</strong></li><li><strong>Jenkins REST API</strong></li></ol><h3>Jenkins CLI</h3><p>The Jenkins CLI is a <strong>Java-based command line interface</strong>.</p><p>Download it from:</p><pre>http://&lt;jenkins-server&gt;/jnlpJars/jenkins-cli.jar</pre><p>Example usage:</p><pre>java -jar jenkins-cli.jar -s http://localhost:8080/ help</pre><p>List jobs:</p><pre>java -jar jenkins-cli.jar -s http://localhost:8080/ list-jobs</pre><p>Identify the current user:</p><pre>java -jar jenkins-cli.jar -s http://localhost:8080/ who-am-i</pre><p>Authentication methods include:</p><ul><li>Username + API Token</li><li>SSH key authentication</li></ul><h3>Jenkins REST API</h3><p>The REST API allows external applications to interact with Jenkins.</p><p>Examples include:</p><ul><li>Trigger builds</li><li>Query job information</li><li>Manage nodes and agents</li></ul><p>Example API call:</p><pre>curl -u USER:TOKEN http://localhost:8080/api/json</pre><p>Trigger a parameterized build:</p><pre>curl -X POST http://localhost:8080/job/example/buildWithParameters \<br>-d PARAM1=value</pre><h3>CSRF Protection in Jenkins</h3><p>Jenkins protects against <strong>Cross-Site Request Forgery (CSRF)</strong> attacks using a token called a <strong>crumb</strong>.</p><p>Before sending POST requests, clients must fetch the crumb:</p><pre>/crumbIssuer/api/json</pre><p>crumb must then be included in request headers.</p><p>This prevents malicious sites from executing unauthorized Jenkins actions.</p><h3>Jenkins Security Best Practices</h3><p>Security in Jenkins revolves around two core concepts:</p><h3>Authentication</h3><p>Verifying a user’s identity.</p><h3>Authorization</h3><p>Defining what actions a user is allowed to perform.</p><h3>Matrix Authorization Strategy</h3><p>The <strong>Matrix Authorization Strategy plugin</strong> allows fine-grained permission management.</p><p>Example roles:</p><ul><li>Administrator</li><li>Manager</li><li>Developer</li><li>QA Engineer</li></ul><p>Each role can be assigned specific permissions such as:</p><ul><li>Build jobs</li><li>Configure pipelines</li><li>Manage credentials</li><li>Administer Jenkins</li></ul><p>Following the <strong>principle of least privilege</strong> ensures that users only have the permissions necessary for their role.</p><h3>Final Thoughts</h3><p>Jenkins remains one of the most powerful and flexible CI/CD tools available.</p><p>Its strengths include:</p><ul><li>Massive plugin ecosystem</li><li>Pipeline-as-code support</li><li>Distributed build architecture</li><li>Deep automation capabilities</li></ul><p>However, the real power of Jenkins comes from <strong>well-designed pipelines and strong security practices</strong>.</p><p>Master those, and Jenkins becomes more than a build server — it becomes the backbone of your entire <strong>software delivery pipeline</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eec94dcd68d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Git Commands: Master the Power Tools (Part 2)]]></title>
            <link>https://medium.com/@nirmalperera2509/advanced-git-commands-master-the-power-tools-part-2-52658de7bc19?source=rss-40963a346e5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/52658de7bc19</guid>
            <category><![CDATA[git-reflog]]></category>
            <category><![CDATA[git-reset]]></category>
            <category><![CDATA[git-stash]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-rebase]]></category>
            <dc:creator><![CDATA[Nirmal Perera]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 10:24:27 GMT</pubDate>
            <atom:updated>2026-02-03T10:24:27.599Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Recovering from disasters, finding bugs, and surgical commit editing</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*uisiDSdEa5Nf2B8D.png" /></figure><p>Welcome back! In <a href="https://medium.com/@nirmalperera2509/advanced-git-commands-master-the-power-tools-part-1-33b0828837ac"><strong><em>Part 1</em></strong></a>, we covered reset, revert, restore, cherry-picking, and the merge vs rebase debate. Now let’s explore Git’s most powerful recovery and debugging tools.</p><h3>What You’ll Learn in Part 2</h3><ul><li>Reflog: Git’s safety net and time machine</li><li>Advanced stashing techniques</li><li>Finding bugs with bisect</li><li>Commit surgery (amending, splitting, reordering)</li><li>Working with patches</li><li>Real-world workflows and best practices</li></ul><h3>Part 5: Reflog — Git’s Time Machine</h3><p>Reflog records all movements of HEAD, acting as a safety net for almost any mistake.</p><h3>Using Reflog to Recover Lost Commits</h3><pre># Create commits<br>echo &quot;Important work&quot; &gt; important.txt<br>git add important.txt<br>git commit -m &quot;Important commit&quot;<br><br># Note the commit hash<br>git log --oneline<br><br><br># Create another commit<br>echo &quot;More work&quot; &gt; more.txt<br>git add more.txt<br>git commit -m &quot;More work&quot;<br><br># Accidentally hard reset (losing commits)<br>git reset --hard HEAD~2<br><br># OH NO! Our work is gone<br>git log --oneline<br><br># But reflog remembers everything<br>git reflog<br><br># Find the commit we want (look for &quot;Important commit&quot;)<br># Recover it<br>    git reset --hard HEAD@{2}<br>    # Or use the commit hash<br>    git reset --hard &lt;commit-hash&gt;<br><br># Our work is back!<br>git log --oneline</pre><h3>Reflog to Undo Rebase</h3><pre># Create scenario<br>git checkout -b feature-reflog-demo<br>echo &quot;Feature work&quot; &gt; feature-work.txt<br>git add feature-work.txt<br>git commit -m &quot;Feature work&quot;<br><br># Do a rebase (that we&#39;ll want to undo)<br>git rebase master<br><br># View reflog<br>git reflog<br><br># Find the state before rebase (look for &quot;checkout: moving from&quot;)<br># Undo the rebase<br>git reset --hard HEAD@{1}</pre><blockquote><strong><em>Pro Tip:</em></strong><em> Reflog is your safety net. Almost any operation can be undone if you act quickly (reflog entries expire after 90 days by default).</em></blockquote><h3>Part 6: Advanced Stashing</h3><p>Stashing is much more powerful than just a simple “save for later” feature.</p><h3>Basic Stash Operations</h3><pre># Make some changes<br>echo &quot;Unstaged work&quot; &gt; unstaged.txt<br>echo &quot;More changes&quot; &gt;&gt; test.txt<br><br># Stash changes<br>git stash<br><br># Or stash with a message<br>git stash push -m &quot;Work in progress on feature X&quot;<br><br># List stashes<br>git stash list<br><br># View stash content<br>git stash show<br># Show full diff<br>git stash show -p<br><br># Apply stash (keep it in stash list)<br>git stash apply<br><br># Apply and remove from list<br>git stash pop<br><br># Apply specific stash<br>git stash apply stash@{1}<br><br># Drop a stash<br>git stash drop stash@{0}<br><br># Clear all stashes<br>git stash clear</pre><h3>Stash Untracked and Ignored Files</h3><pre># Create untracked file<br>echo &quot;New file&quot; &gt; untracked.txt<br><br># Stash including untracked files<br>    git stash -u<br>    # or<br>    git stash --include-untracked<br><br># Stash everything, including ignored files<br>    git stash -a<br>    # or<br>    git stash --all</pre><h3>Create Branch from Stash</h3><pre># Make changes and stash<br>echo &quot;Experimental work&quot; &gt; experiment.txt<br>git add experiment.txt<br>git stash<br><br># Create branch from stash<br>git stash branch feature-from-stash<br># The stash is automatically applied and dropped</pre><h3>Part 7: Advanced Merge Strategies</h3><h3>Merge Strategies</h3><pre># Ours strategy - take our version in conflicts<br>git merge -X ours feature-branch<br><br># Theirs strategy - take their version in conflicts<br>git merge -X theirs feature-branch<br><br># Patience strategy - better diff algorithm<br>git merge -X patience feature-branch</pre><h3>Octopus Merge (Multiple Branches)</h3><pre># Create multiple feature branches<br>git checkout -b feature-1<br><br>echo &quot;Feature 1&quot; &gt; f1.txt<br>git add f1.txt<br>git commit -m &quot;Add feature 1&quot;<br><br>git checkout master<br>git checkout -b feature-2<br><br>echo &quot;Feature 2&quot; &gt; f2.txt<br>git add f2.txt<br>git commit -m &quot;Add feature 2&quot;<br><br>git checkout master<br>git checkout -b feature-3<br><br>echo &quot;Feature 3&quot; &gt; f3.txt<br>git add f3.txt<br>git commit -m &quot;Add feature 3&quot;<br><br># Merge all at once<br>git checkout master<br>git merge feature-1 feature-2 feature-3<br><br># View the octopus merge<br>git log --oneline --graph</pre><h3>Aborting Merges</h3><pre># Start a merge that causes conflicts<br># (Create the scenario as needed)<br><br># If you want to abort<br>git merge --abort<br># Returns to state before merge</pre><h3>Part 8: Finding Bugs with Bisect</h3><p>Bisect uses binary search to find which commit introduced a bug.</p><h3>Binary Search for Bugs</h3><pre># Create a history with a bug<br>git checkout master<br><br>echo &quot;def calculate(): return 2 + 2&quot; &gt; calculator.py<br>git add calculator.py<br>git commit -m &quot;Add calculator - working&quot;<br><br>echo &quot;def calculate(): return 2 + 3&quot; &gt; calculator.py<br>git add calculator.py<br>git commit -m &quot;Update calculator&quot;<br><br>echo &quot;def calculate(): return 2 + 2&quot; &gt; calculator.py<br>echo &quot;# More features&quot; &gt;&gt; calculator.py<br>git add calculator.py<br>git commit -m &quot;Add features&quot;<br><br>echo &quot;def calculate(): return 2 - 2&quot; &gt; calculator.py  # BUG<br>echo &quot;# More features&quot; &gt;&gt; calculator.py<br>git add calculator.py<br>git commit -m &quot;More updates&quot;<br><br>echo &quot;# Even more features&quot; &gt;&gt; calculator.py<br>git add calculator.py<br>git commit -m &quot;Final updates&quot;<br><br># Start bisect<br>git bisect start<br><br># Mark current commit as bad<br>git bisect bad<br><br># Mark a known good commit (e.g., initial commit)<br>git bisect good HEAD~4<br><br># Git checks out middle commit<br># Test it, then mark as good or bad<br>git bisect good<br># or<br># git bisect bad<br># Continue until Git finds the offending commit<br># When done<br>git bisect reset</pre><h3>Automated Bisect</h3><pre># Create a test script<br>echo &#39;#!/bin/bash<br>grep &quot;return 2 + 2&quot; calculator.py&#39; &gt; test.sh<br>chmod +x test.sh<br><br># Run automated bisect<br>git bisect start HEAD HEAD~4<br>git bisect run ./test.sh<br># Git automatically finds the bad commit<br>git bisect reset</pre><h3>Part 9: Commit Surgery</h3><h3>Amending Old Commits</h3><pre># Create commits<br>echo &quot;Version 1&quot; &gt; file.txt<br>git add file.txt<br>git commit -m &quot;Add file&quot;<br><br>echo &quot;Version 2&quot; &gt; another.txt<br>git add another.txt<br>git commit -m &quot;Add another file&quot;<br><br># Oops, forgot something in first commit<br># Use interactive rebase<br>git rebase -i HEAD~2<br><br># Change &#39;pick&#39; to &#39;edit&#39; for the commit to modify<br><br># Git pauses at that commit<br><br># Make your changes<br>echo &quot;Version 1 UPDATED&quot; &gt; file.txt<br>git add file.txt<br>git commit --amend --no-edit<br><br># Continue rebase<br>git rebase --continue</pre><h3>Splitting a Commit</h3><pre># Create a commit with multiple changes<br>echo &quot;Feature A&quot; &gt; feature-a.txt<br>echo &quot;Feature B&quot; &gt; feature-b.txt<br>git add .<br>git commit -m &quot;Add both features&quot;<br><br># Split it using interactive rebase<br>git rebase -i HEAD~1<br><br># Change &#39;pick&#39; to &#39;edit&#39;<br># Git pauses at the commit<br># Undo the commit but keep changes<br>git reset HEAD^<br><br># Now commit separately<br>git add feature-a.txt<br>git commit -m &quot;Add feature A&quot;<br><br>git add feature-b.txt<br>git commit -m &quot;Add feature B&quot;<br><br># Continue rebase<br>git rebase --continue</pre><h3>Reordering Commits</h3><pre># Create commits<br>echo &quot;First&quot; &gt; first.txt<br>git add first.txt<br>git commit -m &quot;First commit&quot;<br><br>echo &quot;Second&quot; &gt; second.txt<br>git add second.txt<br>git commit -m &quot;Second commit&quot;<br><br>echo &quot;Third&quot; &gt; third.txt<br>git add third.txt<br>git commit -m &quot;Third commit&quot;<br><br># Reorder using interactive rebase<br>git rebase -i HEAD~3<br><br># In editor, reorder the lines:<br>pick &lt;hash&gt; Third commit<br>pick &lt;hash&gt; First commit<br>pick &lt;hash&gt; Second commit</pre><h3>Part 10: Advanced Reset Scenarios</h3><h3>Reset Individual Files</h3><pre># Make changes to multiple files<br>echo &quot;Change 1&quot; &gt; file1.txt<br>echo &quot;Change 2&quot; &gt; file2.txt<br>git add .<br>git commit -m &quot;Update both files&quot;<br><br># Make more changes<br>echo &quot;Another change&quot; &gt;&gt; file1.txt<br>echo &quot;Another change&quot; &gt;&gt; file2.txt<br>git add .<br><br># Reset only file1 to previous commit<br>git reset HEAD~1 -- file1.txt<br><br># file1.txt is unstaged, file2.txt remains staged<br>git status</pre><h3>Soft Reset for Combining Commits</h3><pre># Create several small commits<br>echo &quot;Part 1&quot; &gt; work.txt<br>git add work.txt<br>git commit -m &quot;Part 1&quot;<br><br>echo &quot;Part 2&quot; &gt;&gt; work.txt<br>git add work.txt<br>git commit -m &quot;Part 2&quot;<br><br>echo &quot;Part 3&quot; &gt;&gt; work.txt<br>git add work.txt<br>git commit -m &quot;Part 3&quot;<br><br># Combine them into one<br>git reset --soft HEAD~3<br><br># All changes are staged<br>git status<br><br># Commit as one<br>git commit -m &quot;Complete work (all parts)&quot;</pre><h3>Part 11: Working with Patches</h3><h3>Creating and Applying Patches</h3><pre># Make changes<br>echo &quot;New feature&quot; &gt; feature.txt<br>git add feature.txt<br>git commit -m &quot;Add new feature&quot;<br><br># Create a patch file<br>git format-patch -1 HEAD<br># This creates a .patch file<br><br># Apply patch (in another repo or branch)<br>git checkout -b apply-patch-demo<br>git apply 0001-Add-new-feature.patch<br># Or apply as a commit<br>git am 0001-Add-new-feature.patch</pre><h3>Patch from Diff</h3><pre># Make uncommitted changes<br>echo &quot;Modified content&quot; &gt; test.txt<br><br># Create patch from diff<br>git diff &gt; my-changes.patch<br><br># Revert changes<br>git restore test.txt<br><br># Apply patch later<br>git apply my-changes.patch</pre><h3>Advanced Commands Quick Reference</h3><h3>Reflog</h3><pre>git reflog                         # Show reference log<br>git reflog show &lt;branch&gt;           # Show reflog for branch<br>git reset --hard HEAD@{2}          # Reset to reflog entry</pre><h3>Stash</h3><pre>git stash                          # Stash changes<br>git stash -u                       # Include untracked files<br>git stash list                     # List stashes<br>git stash apply                    # Apply latest stash<br>git stash pop                      # Apply and remove stash<br>git stash drop                     # Remove stash<br>git stash clear                    # Remove all stashes<br>git stash branch &lt;name&gt;            # Create branch from stash</pre><h3>Bisect</h3><pre>git bisect start                   # Start bisect<br>git bisect bad                     # Mark current as bad<br>git bisect good &lt;commit&gt;           # Mark commit as good<br>git bisect reset                   # End bisect<br>git bisect run &lt;script&gt;            # Automated bisect</pre><h3>Advanced Merge</h3><pre>git merge -X ours &lt;branch&gt;         # Prefer our changes<br>git merge -X theirs &lt;branch&gt;       # Prefer their changes<br>git merge --abort                  # Cancel merge<br>git merge --squash &lt;branch&gt;        # Squash merge</pre><h3>Decision Matrix: Which Command to Use?</h3><h3>Undoing Changes</h3><p>Scenario Command Safe for Shared? Undo last commit, keep changes git reset --soft HEAD~1 ❌ No Undo last commit, unstage changes git reset HEAD~1 ❌ No Undo last commit, destroy changes git reset --hard HEAD~1 ❌ No Undo pushed commit git revert &lt;commit&gt; ✅ Yes Unstage file git restore --staged &lt;file&gt; ✅ Yes Discard working changes git restore &lt;file&gt; ✅ Yes</p><h3>Combining Changes</h3><p>Goal Command Best For Clean linear history git rebase Personal branches Preserve branch context git merge Shared branches Combine specific commits git cherry-pick Selective porting Clean up messy commits git rebase -i Before sharing Squash feature branch git merge --squash Clean master history</p><h3>Real-World Workflows</h3><h3>Workflow 1: Feature Development</h3><pre># Start feature<br>git checkout -b feature/user-auth<br><br># Work and commit<br>git add .<br>git commit -m &quot;feat: implement login&quot;<br><br># Update with master<br>git fetch origin<br>git rebase origin/master<br><br># Clean up commits<br>git rebase -i origin/master<br><br># Push<br>git push origin feature/user-auth<br><br># Merge via pull request</pre><h3>Workflow 2: Hotfix on Production</h3><pre># Create hotfix branch<br>git checkout -b hotfix/critical-bug master<br><br># Fix and commit<br>git add .<br>git commit -m &quot;fix: resolve critical security issue&quot;<br><br># Merge to master<br>git checkout master<br>git merge hotfix/critical-bug<br>git push origin master<br><br># Also merge to development<br>git checkout develop<br>git merge hotfix/critical-bug<br>git push origin develop<br><br># Delete hotfix branch<br>git branch -d hotfix/critical-bug</pre><h3>Workflow 3: Recovering from Mistakes</h3><pre># Oops, committed to master instead of feature branch<br>git checkout -b feature/moved-work<br>git checkout master<br>git reset --hard HEAD~1<br><br># Or: accidentally deleted work<br>git reflog<br>git reset --hard HEAD@{5}</pre><h3>Advanced Scenarios Walkthrough</h3><h3>Scenario 1: Squashing Multiple Commits Before PR</h3><pre># You have 5 commits<br>git log --oneline -5<br><br># Squash into one<br>git rebase -i HEAD~5<br><br># In editor:<br>pick commit1<br>squash commit2<br>squash commit3<br>squash commit4<br>squash commit5<br><br># Edit combined commit message<br>Force push (only on YOUR branch)<br>git push --force-with-lease</pre><h3>Scenario 2: Splitting a Large Commit</h3><pre># You have one large commit<br>git rebase -i HEAD~1<br># Mark as &#39;edit&#39;<br><br># Reset but keep changes<br>git reset HEAD^<br><br># Selectively stage and commit<br>git add feature1.py<br>git commit -m &quot;feat: add feature 1&quot;<br><br>git add feature2.py<br>git commit -m &quot;feat: add feature 2&quot;<br><br>git rebase --continue</pre><h3>Scenario 3: Undoing a Published Merge</h3><pre># Find the merge commit<br>git log --oneline --merges<br><br># Revert it (creates new commit)<br>git revert -m 1 &lt;merge-commit-hash&gt;<br><br># Push<br>git push origin master</pre><h3>Pro Tips and Best Practices</h3><h3>1. Commit Message Conventions</h3><pre># Use conventional commits format<br>git commit -m &quot;feat: add user authentication&quot;<br>git commit -m &quot;fix: resolve login bug&quot;<br>git commit -m &quot;docs: update API documentation&quot;<br>git commit -m &quot;refactor: simplify payment logic&quot;<br>git commit -m &quot;test: add unit tests for parser&quot;</pre><h3>2. Alias for Productivity</h3><p>Add these to your ~/.gitconfig:</p><pre>git config --global alias.st status<br>git config --global alias.co checkout<br>git config --global alias.br branch<br>git config --global alias.ci commit<br>git config --global alias.unstage &#39;reset HEAD --&#39;<br>git config --global alias.last &#39;log -1 HEAD&#39;<br>git config --global alias.visual &#39;log --oneline --graph --all&#39;<br>git config --global alias.amend &#39;commit --amend --no-edit&#39;</pre><h3>3. Safety Checks Before Dangerous Operations</h3><pre># Before hard reset<br>git log --oneline  # Know what you&#39;re losing<br>git reflog         # Safety net<br><br># Before force push<br>git log origin/master..HEAD  # What you&#39;re about to overwrite<br>git push --force-with-lease # Safer than --force<br><br># Before rebase<br>git checkout -b backup-branch  # Create backup<br>git rebase master<br># If problems: git rebase --abort</pre><h3>4. Recovery Techniques</h3><pre># Recover deleted branch<br>git reflog<br>git checkout -b recovered-branch &lt;commit-hash&gt;<br><br># Recover deleted files<br>git checkout &lt;commit-hash&gt; -- &lt;file-path&gt;<br><br># Find lost commits<br>git fsck --lost-found</pre><h3>5. Performance Tips</h3><pre># Speed up status on large repos<br>git config core.fsmonitor true<br><br># Shallow clone for large repos<br>git clone --depth 1 &lt;repository-url&gt;<br><br># Garbage collection<br>git gc --aggressive</pre><h3>Common Pitfalls and How to Avoid Them</h3><h3>1. Don’t Rebase Shared Branches</h3><pre># ❌ NEVER DO THIS<br>git checkout master<br>git rebase feature  # master is shared!<br><br># ✅ DO THIS INSTEAD<br>git checkout master<br>git merge feature</pre><h3>2. Check What You’re Resetting</h3><pre># ❌ Blind reset<br>git reset --hard HEAD~5<br><br># ✅ Safe approach<br><br># Check what you&#39;re resetting<br>git log --oneline -10  <br><br># Use soft first<br>git reset --soft HEAD~5  <br><br># Verify before hard reset</pre><h3>3. Stash Before Switching Branches</h3><pre># ❌ Switch with uncommitted changes<br># May lose work<br>git checkout other-branch  <br><br>git stash<br>git checkout other-branch<br><br># Later: <br>git stash pop</pre><h3>4. Don’t Cherry-Pick Merge Commits</h3><pre># ❌ Cherry-pick merge commits directly<br>git cherry-pick &lt;merge-commit&gt;  # Ambiguous<br><br># ✅ Specify parent<br>git cherry-pick -m 1 &lt;merge-commit&gt;</pre><h3>Conclusion</h3><p>These advanced Git commands give you surgical precision over your repository history. Remember the key principles:</p><h3>The Golden Rules</h3><ol><li><strong>Safety First</strong>: Always check git status and git log before destructive operations</li><li><strong>Reflog is Your Friend</strong>: You can almost always recover with git reflog</li><li><strong>Never Rewrite Shared History</strong>: Use revert instead of reset/rebase on public branches</li><li><strong>Practice in Safe Environments</strong>: Try these commands in test repositories first</li><li><strong>Backup Before Experiments</strong>: Create backup branches before complex operations</li></ol><p>Mastering these commands transforms Git from a simple version control tool into a powerful time machine for your code. The key is knowing which tool to use for each situation.</p><p>Keep experimenting, and don’t fear mistakes — Git’s design makes almost everything recoverable!</p><h3>Further Learning</h3><ul><li><a href="https://git-scm.com/doc">Git Documentation</a></li><li><a href="https://git-scm.com/book/en/v2">Pro Git Book — Advanced Topics</a></li><li><a href="https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain">Git Internals</a></li><li>Practice: <a href="https://learngitbranching.js.org/">Learn Git Branching</a></li></ul><p><em>Did you find this guide helpful? </em><a href="https://medium.com/@nirmalperera2509/advanced-git-commands-master-the-power-tools-part-1-33b0828837ac"><em>Part 1</em></a><em> covered reset, revert, restore, cherry-picking, and merge vs rebase. Together, these two parts give you a complete toolkit for advanced Git operations.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52658de7bc19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Git Commands: Master the Power Tools (Part 1)]]></title>
            <link>https://medium.com/@nirmalperera2509/advanced-git-commands-master-the-power-tools-part-1-33b0828837ac?source=rss-40963a346e5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/33b0828837ac</guid>
            <category><![CDATA[git-cherry-pick]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-merge-vs-rebase]]></category>
            <category><![CDATA[git-reset]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Nirmal Perera]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 02:37:02 GMT</pubDate>
            <atom:updated>2026-01-29T02:37:02.104Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A comprehensive hands-on guide to mastering Git’s most powerful features</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*WzZPx-wuJhF4nrtC.png" /></figure><p>After mastering Git basics, it’s time to level up. This comprehensive guide covers advanced Git operations that will make you a version control expert. We’ll explore commit manipulation, history rewriting, and sophisticated branching strategies — all through hands-on examples in a single repository.</p><h3>What You’ll Learn</h3><p>In Part 1, we’ll cover:</p><ul><li>Understanding and using git reset, git revert, and git restore</li><li>Cherry-picking commits across branches</li><li>Rebasing vs merging: when to use each</li><li>Interactive rebasing for clean history</li><li>Undoing pushed commits safely</li></ul><h3>Prerequisites</h3><p>You should be comfortable with basic Git commands (init, add, commit, branch, merge). If you need a refresher, check out our beginner’s guide.</p><h3>Setup: Create Our Practice Repository</h3><p>Let’s start by creating a practice repository where we can safely experiment:</p><pre># Create a new directory<br>mkdir advanced-git-guide<br>cd advanced-git-guide<br><br># Initialize repository<br>git init<br><br># Configure (if needed)<br>git config user.name &quot;Your Name&quot;<br>git config user.email &quot;your.email@example.com&quot;<br><br># Create initial commit<br>echo &quot;# Advanced Git Guide&quot; &gt; test.txt<br>git add test.txt<br>git commit -m &quot;Initial commit&quot;</pre><h3>Part 1: Understanding Reset, Restore, and Revert</h3><p>These three commands are often confused but serve different purposes. Let’s demystify them.</p><h3>Understanding git reset</h3><p>Reset moves the current branch pointer to a different commit. There are three modes: soft, mixed, and hard.</p><p>First, let’s create some commits to work with:</p><pre># Create some commits to work with<br>echo &quot;Feature A&quot; &gt; feature-a.txt<br>git add feature-a.txt<br>git commit -m &quot;Add feature A&quot;<br><br>echo &quot;Feature B&quot; &gt; feature-b.txt<br>git add feature-b.txt<br>git commit -m &quot;Add feature B&quot;<br><br>echo &quot;Feature C&quot; &gt; feature-c.txt<br>git add feature-c.txt<br>git commit -m &quot;Add feature C&quot;<br><br># View your history<br>git log --oneline</pre><h3>Soft Reset (Keep Changes Staged)</h3><pre># Reset to one commit back, keeping changes staged<br>git reset --soft HEAD~1<br><br># Check status - feature-c.txt is still staged<br>git status<br><br># View log - &quot;Add feature C&quot; commit is gone<br>git log --oneline<br><br># Recommit if you want<br>git commit -m &quot;Add feature C (recommitted)&quot;</pre><h3>Mixed Reset (Default — Keep Changes Unstaged)</h3><pre># Reset to one commit back, keeping changes unstaged<br>git reset HEAD~1<br># or simply: git reset HEAD~1 (mixed is default)</pre><pre><br># Check status - feature-c.txt is unstaged but exists<br>git status<br><br># Re-stage and commit<br>git add feature-c.txt<br>git commit -m &quot;Add feature C again&quot;</pre><h3>Hard Reset (Discard Changes Completely)</h3><pre># Create a temporary commit<br>echo &quot;Temporary feature&quot; &gt; temp.txt<br>git add temp.txt<br>git commit -m &quot;Temporary commit&quot;<br><br># Hard reset - DESTROYS the commit and changes<br>git reset --hard HEAD~1<br><br># temp.txt is completely gone<br>git log --oneline</pre><blockquote><em>⚠️ </em><strong><em>Warning:</em></strong><em> </em><em>--hard permanently deletes uncommitted changes. Use with caution!</em></blockquote><h3>Understanding git revert</h3><p>Unlike reset, revert creates a NEW commit that undoes previous changes. This makes it safe for shared branches.</p><pre># Create a commit we&#39;ll want to undo<br>echo &quot;Bug introduced here&quot; &gt; bug.txt<br>git add bug.txt<br>git commit -m &quot;Add buggy feature&quot;<br><br># Create more commits after it<br>echo &quot;More work&quot; &gt; work.txt<br>git add work.txt<br>git commit -m &quot;Continue development&quot;<br><br># Revert the buggy commit (Git will open editor for commit message)<br>git revert HEAD~1<br># Or specify commit hash<br># git revert &lt;commit-hash&gt;<br><br># Check log - you&#39;ll see a new &quot;Revert&quot; commit<br>git log --oneline<br><br># bug.txt is now gone, but work.txt remains</pre><p><strong>Key Difference:</strong> Revert is safe for public/shared branches because it doesn’t rewrite history.</p><h3>Understanding git restore</h3><p>Restore is a newer command (Git 2.23+) that replaces some uses of checkout.</p><pre># Make changes to a file<br>echo &quot;Unwanted changes&quot; &gt;&gt; test.txt<br>git status<br><br># Restore file to last committed state<br>git restore test.txt<br>git status<br><br># Stage a change<br>echo &quot;New feature&quot; &gt; new-feature.txt<br>git add new-feature.txt<br>git status<br><br># Unstage the file<br>git restore --staged new-feature.txt<br>git status<br><br># Restore from a specific commit<br>echo &quot;Current content&quot; &gt; test.txt<br>git add test.txt<br>git commit -m &quot;Update text file&quot;<br><br># Restore to 2 commits ago<br>git restore --source=HEAD~2 test.txt</pre><h3>Part 2: Cherry-Picking Commits</h3><p>Cherry-pick allows you to copy specific commits from one branch to another.</p><h3>Basic Cherry-Pick</h3><pre># Create a feature branch<br>git checkout -b feature-experimental<br><br># Make several commits<br>echo &quot;Experiment 1&quot; &gt; exp1.txt<br>git add exp1.txt<br>git commit -m &quot;Experiment 1&quot;<br><br>echo &quot;Experiment 2&quot; &gt; exp2.txt<br>git add exp2.txt<br>git commit -m &quot;Experiment 2&quot;<br><br>echo &quot;Experiment 3&quot; &gt; exp3.txt<br>git add exp3.txt<br>git commit -m &quot;Experiment 3&quot;<br><br># Note the commit hash of &quot;Experiment 2&quot;<br>git log --oneline<br><br># Switch back to master<br>git checkout master<br><br># Cherry-pick only &quot;Experiment 2&quot; commit<br>git cherry-pick &lt;commit-hash-of-experiment-2&gt;<br><br># Verify - only exp2.txt is here<br>git log --oneline</pre><h3>Cherry-Pick Multiple Commits</h3><pre># Cherry-pick a range of commits<br>git cherry-pick &lt;oldest-commit-hash&gt;..&lt;newest-commit-hash&gt;<br><br># Or cherry-pick multiple specific commits<br>git cherry-pick &lt;commit-hash-1&gt; &lt;commit-hash-2&gt;</pre><h3>Handling Cherry-Pick Conflicts</h3><pre># Create conflict scenario<br>echo &quot;Version A&quot; &gt; conflict-file.txt<br>git add conflict-file.txt<br>git commit -m &quot;Add conflict file on master&quot;<br><br># On feature branch, modify the same file<br>git checkout feature-experimental<br>echo &quot;Version B&quot; &gt; conflict-file.txt<br>git add conflict-file.txt<br>git commit -m &quot;Add conflict file on feature&quot;<br><br># Save this commit hash<br>git log --oneline<br><br># Try to cherry-pick - will cause conflict<br>git checkout master<br>git cherry-pick &lt;commit-hash&gt;<br><br># Resolve conflict manually in conflict-file.txt<br>    # Then continue<br>        git add conflict-file.txt<br>        git cherry-pick --continue<br><br>    # Or abort if needed<br>        git cherry-pick --abort</pre><h3>Part 3: Merge vs Rebase</h3><h3>Understanding Merge</h3><p>Merge creates a merge commit, preserving branch history.</p><pre># Start fresh for clarity<br>git checkout master<br><br># Create a feature branch<br>git checkout -b feature-merge-demo<br><br># Make commits on feature branch<br>echo &quot;Feature commit 1&quot; &gt; merge-feature-1.txt<br>git add merge-feature-1.txt<br>git commit -m &quot;Feature merge commit 1&quot;<br><br>echo &quot;Feature commit 2&quot; &gt; merge-feature-2.txt<br>git add merge-feature-2.txt<br>git commit -m &quot;Feature merge commit 2&quot;<br><br># Switch to master and make commits<br>git checkout master<br><br>echo &quot;master commit 1&quot; &gt; master-work-1.txt<br>git add master-work-1.txt<br>git commit -m &quot;master commit 1&quot;<br><br># Merge feature branch into master<br>git merge feature-merge-demo<br><br># View the history graph<br>git log --oneline --graph --all</pre><p><strong>Result:</strong> You’ll see a merge commit with two parent commits, preserving full history.</p><h3>Understanding Rebase</h3><p>Rebase rewrites history by moving commits to a new base.</p><pre># Create another feature branch<br>git checkout -b feature-rebase-demo<br><br># Make commits<br>echo &quot;Rebase feature 1&quot; &gt; rebase-feature-1.txt<br>git add rebase-feature-1.txt<br>git commit -m &quot;Rebase feature commit 1&quot;<br><br>echo &quot;Rebase feature 2&quot; &gt; rebase-feature-2.txt<br>git add rebase-feature-2.txt<br>git commit -m &quot;Rebase feature commit 2&quot;<br><br># Switch to master and make commits<br>git checkout master<br>echo &quot;More master work&quot; &gt; master-work-2.txt<br>git add master-work-2.txt<br>git commit -m &quot;master commit 2&quot;<br><br># Rebase feature branch onto master<br>git checkout feature-rebase-demo<br>git rebase master<br><br># View the linear history<br>git log --oneline --graph --all</pre><p><strong>Result:</strong> A clean, linear history without merge commits.</p><h3>Interactive Rebase — History Cleanup</h3><p>Interactive rebase is incredibly powerful for cleaning up commit history.</p><pre># Create messy commits<br>echo &quot;Work part 1&quot; &gt; interactive-demo.txt<br>git add interactive-demo.txt<br>git commit -m &quot;WIP: started work&quot;<br><br>echo &quot;Work part 2&quot; &gt;&gt; interactive-demo.txt<br>git add interactive-demo.txt<br>git commit -m &quot;more stuff&quot;<br><br>echo &quot;Work part 3&quot; &gt;&gt; interactive-demo.txt<br>git add interactive-demo.txt<br>git commit -m &quot;oops typo fix&quot;<br><br>echo &quot;Work part 4&quot; &gt;&gt; interactive-demo.txt<br>git add interactive-demo.txt<br>git commit -m &quot;Final version&quot;<br><br># View messy history<br>git log --oneline<br><br># Interactive rebase last 4 commits<br>git rebase -i HEAD~4</pre><p><strong>In the editor that opens:</strong></p><pre>pick abc1234 WIP: started work<br>squash def5678 more stuff<br>squash ghi9012 oops typo fix<br>pick jkl3456 Final version</pre><h3>Common commands in interactive rebase:</h3><ul><li>pick (p) - Keep commit as-is</li><li>reword (r) - Keep commit but edit message</li><li>edit (e) - Stop to amend commit</li><li>squash (s) - Combine with previous commit, keep both messages</li><li>fixup (f) - Combine with previous commit, discard this message</li><li>drop (d) - Remove commit entirely</li></ul><h3>Rebase with Conflicts</h3><pre># Create conflict scenario<br>git checkout master<br>echo &quot;master version&quot; &gt; conflict-rebase.txt<br>git add conflict-rebase.txt<br>git commit -m &quot;Add file on master&quot;<br><br>git checkout -b feature-conflict<br>echo &quot;Feature version&quot; &gt; conflict-rebase.txt<br>git add conflict-rebase.txt<br>git commit -m &quot;Modify file on feature&quot;<br><br># Meanwhile, master progresses<br>git checkout master<br>echo &quot;master version updated&quot; &gt; conflict-rebase.txt<br>git add conflict-rebase.txt<br>git commit -m &quot;Update file on master&quot;<br><br># Try to rebase - will conflict<br>git checkout feature-conflict<br>git rebase master<br><br># Resolve conflict in conflict-rebase.txt<br>    # Then continue<br>        git add conflict-rebase.txt<br>        git rebase --continue<br>    # Or abort<br>        git rebase --abort</pre><h3>When to Use Merge vs Rebase</h3><h3>Use Merge When:</h3><ul><li>Working on a public/shared branch</li><li>You want to preserve exact history and context</li><li>Working with other team members on the same branch</li></ul><h3>Use Rebase When:</h3><ul><li>Cleaning up local commits before pushing</li><li>Maintaining a linear project history</li><li>Working on a feature branch alone</li></ul><blockquote><strong><em>Golden Rule:</em></strong><em> Never rebase commits that have been pushed to a shared branch!</em></blockquote><h3>Part 4: Undoing Pushed Commits</h3><h3>Revert Pushed Commits (Safe Method)</h3><pre># Simulate a pushed commit (we&#39;ll just commit to master)<br>echo &quot;Bad code pushed&quot; &gt; bad-code.txt<br>git add bad-code.txt<br>git commit -m &quot;Add bad code&quot;<br><br># Simulate more work after<br>echo &quot;Good work&quot; &gt; good-work.txt<br>git add good-work.txt<br>git commit -m &quot;Add good work&quot;<br><br># Safely undo the bad commit with revert<br>git revert HEAD~1<br><br># This creates a new commit that undoes changes<br>git log --oneline</pre><h3>Force Push with Reset (Dangerous!)</h3><pre># Create a branch to demonstrate (never do this on shared branches!)<br>git checkout -b demo-force-push<br><br># Make commits<br>echo &quot;Commit 1&quot; &gt; file1.txt<br>git add file1.txt<br>git commit -m &quot;Commit 1&quot;<br><br>echo &quot;Commit 2&quot; &gt; file2.txt<br>git add file2.txt<br>git commit -m &quot;Commit 2&quot;<br><br>echo &quot;Commit 3 - OOPS&quot; &gt; file3.txt<br>git add file3.txt<br>git commit -m &quot;Commit 3 - mistake&quot;<br><br># Reset to remove last commit<br>git reset --hard HEAD~1<br><br># If this were pushed, you&#39;d need force push<br>git push --force origin demo-force-push<br># ⚠️ NEVER force push to shared branches like master!</pre><h3>Safer Alternative: Use --force-with-lease</h3><pre># This will fail if someone else has pushed changes<br>git push --force-with-lease origin demo-force-push</pre><h3>Quick Reference: Commands We’ve Covered</h3><h3>Reset Variants</h3><pre>git reset --soft HEAD~1    # Undo commit, keep changes staged<br>git reset HEAD~1           # Undo commit, keep changes unstaged<br>git reset --hard HEAD~1    # Undo commit, destroy changes<br>git reset &lt;file&gt;           # Unstage file</pre><h3>Revert</h3><pre>git revert &lt;commit&gt;        # Create new commit undoing changes<br>git revert -n &lt;commit&gt;     # Revert without committing<br>git revert HEAD~3..HEAD    # Revert range of commits</pre><h3>Cherry-Pick</h3><pre>git cherry-pick &lt;commit&gt;              # Copy commit to current branch<br>git cherry-pick &lt;commit1&gt; &lt;commit2&gt;   # Multiple commits<br>git cherry-pick --continue            # After resolving conflicts<br>git cherry-pick --abort               # Cancel cherry-pick</pre><h3>Rebase</h3><pre>git rebase master                  # Rebase current branch onto master<br>git rebase -i HEAD~5               # Interactive rebase last 5 commits<br>git rebase --continue              # Continue after resolving conflicts<br>git rebase --abort                 # Cancel rebase<br>git rebase --skip                  # Skip current commit</pre><h3>Key Takeaways from Part 1</h3><ol><li><strong>Reset</strong> moves your branch pointer and can keep or discard changes depending on the mode (--soft, --mixed, --hard)</li><li><strong>Revert</strong> creates new commits that undo changes — safe for shared branches</li><li><strong>Restore</strong> is the modern way to unstage files or discard working directory changes</li><li><strong>Cherry-pick</strong> lets you selectively copy commits between branches</li><li><strong>Rebase</strong> rewrites history for a cleaner, linear commit history — but never use it on shared branches</li><li><strong>Interactive rebase</strong> is your tool for cleaning up messy commit history before sharing your work</li></ol><h3>Coming Up in Part 2</h3><p>In Part 2, we’ll dive into:</p><ul><li>Reflog: Git’s safety net and time machine</li><li>Advanced stashing techniques</li><li>Finding bugs with bisect</li><li>Commit surgery (amending, splitting, reordering)</li><li>Working with patches</li><li>Real-world workflows and scenarios</li></ul><p><strong>Continue to Part 2</strong> to learn about Git’s most powerful recovery and debugging tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33b0828837ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Git Commands: A Complete Hands-On Guide]]></title>
            <link>https://medium.com/@nirmalperera2509/master-git-commands-a-complete-hands-on-guide-3351af223b5c?source=rss-40963a346e5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3351af223b5c</guid>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-merge]]></category>
            <category><![CDATA[git-branch]]></category>
            <dc:creator><![CDATA[Nirmal Perera]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 23:36:06 GMT</pubDate>
            <atom:updated>2026-01-26T23:36:06.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qi_q30sPyNMqnjle.png" /></figure><p>Git is the backbone of modern software development, yet many developers only scratch the surface of its capabilities. In this guide, you’ll learn essential Git commands through a practical, step-by-step flow using a single repository.</p><h3>What You’ll Learn</h3><p>By the end of this guide, you’ll be comfortable with:</p><ul><li>Repository initialization and configuration</li><li>Basic file operations and staging</li><li>Committing changes effectively</li><li>Branch management and merging</li><li>Viewing history and understanding your project’s evolution</li><li>Undoing changes safely</li><li>Working with remote repositories</li></ul><h3>Prerequisites</h3><p>Before starting, ensure you have Git installed on your system. Check by running:</p><pre>git --version</pre><p>If you don’t have Git installed, download it from <a href="https://git-scm.com/">git-scm.com</a>.</p><h3>Step-by-Step Guide</h3><h3>Step 1: Create and Initialize a Repository</h3><p>Let’s start by creating a new directory and initializing it as a Git repository.</p><pre># Create a new directory for our project<br>mkdir git-guide<br>cd git-guide</pre><pre># Initialize a new Git repository<br>git init</pre><p><strong>What happened?</strong> Git created a hidden .git folder that stores all version control information.</p><h3>Step 2: Configure Git (First-Time Setup)</h3><p>Set your identity so Git knows who is making commits.</p><pre># Set your name<br>git config --global user.name &quot;Your Name&quot;</pre><pre># Set your email<br>git config --global user.email &quot;your.email@example.com&quot;</pre><pre># View your configuration<br>git config --list</pre><h3>Step 3: Create Your First File</h3><p>Create a simple file to start tracking.</p><pre># Create a text file<br>echo &quot;# My Git Tutorial Project&quot; &gt; test.txt</pre><pre># Check the status of your repository<br>git status</pre><p><strong>Understanding </strong><strong>git status:</strong> This command shows you which files are untracked, modified, or staged for commit.</p><h3>Step 4: Stage Changes</h3><p>Before committing, you need to stage files (add them to the staging area).</p><pre># Add test.txt to the staging area<br>git add test.txt</pre><pre># Check status again<br>git status</pre><p>You can also stage all files at once:</p><pre># Stage all changes<br>git add .</pre><h3>Step 5: Make Your First Commit</h3><p>Commits are snapshots of your project at a specific point in time.</p><pre># Commit with a descriptive message<br>git commit -m &quot;Initial commit: Add text file&quot;</pre><pre># View commit history<br>git log</pre><h3>Step 6: Make More Changes</h3><p>Let’s add more content and practice the workflow.</p><pre># Add content to text file<br>echo &quot;This project demonstrates Git commands.&quot; &gt;&gt; test.txt</pre><pre># Create a new file<br>echo &quot;print(&#39;Hello, Git!&#39;)&quot; &gt; hello.py</pre><pre># Check what changed<br>git status</pre><pre># See the exact changes in tracked files<br>git diff</pre><h3>Step 7: Stage and Commit Multiple Files</h3><pre># Stage both files<br>git add test.txt hello.py</pre><pre># Commit the changes<br>git commit -m &quot;Add project description and Python script&quot;</pre><pre># View concise commit history<br>git log --oneline</pre><h3>Step 8: Working with Branches</h3><p>Branches allow you to work on features independently.</p><pre># Create a new branch<br>git branch feature-greeting</pre><pre># List all branches<br>git branch</pre><pre># Switch to the new branch<br>git checkout feature-greeting</pre><pre># Or create and switch in one command<br>git checkout -b feature-goodbye</pre><h3>Step 9: Make Changes on a Branch</h3><pre># Make sure you&#39;re on feature-goodbye branch<br>git branch</pre><pre># Create a new file<br>echo &quot;print(&#39;Goodbye, Git!&#39;)&quot; &gt; goodbye.py</pre><pre># Stage and commit<br>git add goodbye.py<br>git commit -m &quot;Add goodbye script&quot;</pre><h3>Step 10: Switch Between Branches</h3><pre># Switch back to master branch<br>git checkout master</pre><pre># Notice that goodbye.py doesn&#39;t exist here<br>ls</pre><pre># Switch back to feature-goodbye<br>git checkout feature-goodbye</pre><pre># Now goodbye.py exists<br>ls</pre><h3>Step 11: Merge Branches</h3><p>Merge the feature branch back into master.</p><pre># Switch to the branch you want to merge INTO<br>git checkout master</pre><pre># Merge feature-goodbye into master<br>git merge feature-goodbye</pre><pre># Check that goodbye.py now exists in master<br>ls</pre><pre># View the updated log<br>git log --oneline --graph --all</pre><h3>Step 12: Handle a Merge Conflict (Simulated)</h3><p>Let’s create a scenario where conflicts occur.</p><pre># Create and switch to a new branch<br>git checkout -b feature-update-text</pre><pre># Modify text<br>echo &quot;Updated on feature branch&quot; &gt;&gt; test.txt<br>git add test.txt<br>git commit -m &quot;Update text on feature branch&quot;</pre><pre># Switch back to master<br>git checkout master</pre><pre># Make a different change to the same file<br>echo &quot;Updated on master branch&quot; &gt;&gt; test.txt<br>git add test.txt<br>git commit -m &quot;Update text on master branch&quot;</pre><pre># Try to merge - this will cause a conflict<br>git merge feature-update-text</pre><p><strong>Resolving the conflict:</strong></p><pre># View the conflict<br>cat test.txt</pre><pre># Open test.txt in a text editor and manually resolve the conflict<br># Remove the conflict markers (&lt;&lt;&lt;&lt;&lt;&lt;&lt;, =======, &gt;&gt;&gt;&gt;&gt;&gt;&gt;)<br># Keep the content you want</pre><pre># After resolving, stage the file<br>git add test.txt</pre><pre># Complete the merge<br>git commit -m &quot;Resolve merge conflict in test.txt&quot;</pre><h3>Step 13: View History in Detail</h3><pre># View detailed commit history<br>git log</pre><pre># View compact history<br>git log --oneline</pre><pre># View history with graph<br>git log --oneline --graph --all</pre><pre># View changes in a specific commit<br>git show &lt;commit-hash&gt;</pre><pre># View changes for a specific file<br>git log -p test.txt</pre><h3>Step 14: Undoing Changes</h3><p>There are several ways to undo changes depending on what you need.</p><pre># Unstage a file (keep changes in working directory)<br>echo &quot;Temporary change&quot; &gt;&gt; hello.py<br>git add hello.py<br>git reset hello.py</pre><pre># Discard changes in working directory<br>git checkout -- hello.py</pre><pre># Or use the newer restore command<br>git restore hello.py</pre><pre># Amend the last commit (before pushing)<br>echo &quot;Additional info&quot; &gt;&gt; test.txt<br>git add test.txt<br>git commit --amend -m &quot;Update text file with additional info&quot;</pre><h3>Step 15: Working with Remote Repositories</h3><p>While we can’t push to an actual remote without setting one up, here are the commands:</p><pre># Add a remote repository<br>git remote add origin https://github.com/yourusername/your-repo.git</pre><pre># View remotes<br>git remote -v</pre><pre># Push to remote (master branch)<br>git push -u origin master</pre><pre># Pull changes from remote<br>git pull origin master</pre><pre># Clone a repository<br>git clone <a href="https://github.com/username/repository.git">https://github.com/username/repository.git</a></pre><h3>Step 16: Useful Additional Commands</h3><pre># Create a .gitignore file to exclude files<br>echo &quot;*.log&quot; &gt; .gitignore<br>echo &quot;node_modules/&quot; &gt;&gt; .gitignore<br>git add .gitignore<br>git commit -m &quot;Add gitignore&quot;</pre><pre># Rename a file<br>git mv hello.py greet.py<br>git commit -m &quot;Rename hello.py to greet.py&quot;</pre><pre># Delete a file<br>git rm goodbye.py<br>git commit -m &quot;Remove goodbye.py&quot;</pre><pre># Stash changes temporarily<br>echo &quot;Work in progress&quot; &gt;&gt; test.txt<br>git stash<br>git stash list<br>git stash apply</pre><pre># Tag a release<br>git tag v1.0.0<br>git tag -a v1.0.1 -m &quot;Version 1.0.1 release&quot;<br>git tag</pre><h3>Quick Reference Cheat Sheet</h3><h3>Repository Setup</h3><ul><li>git init — Initialize a new repository</li><li>git clone &lt;url&gt; — Clone an existing repository</li></ul><h3>Basic Operations</h3><ul><li>git status — Check repository status</li><li>git add &lt;file&gt; — Stage a file</li><li>git add . — Stage all changes</li><li>git commit -m &quot;message&quot; — Commit staged changes</li><li>git diff — View unstaged changes</li></ul><h3>Branch Management</h3><ul><li>git branch — List branches</li><li>git branch &lt;name&gt; — Create a branch</li><li>git checkout &lt;branch&gt; — Switch branches</li><li>git checkout -b &lt;name&gt; — Create and switch to a branch</li><li>git merge &lt;branch&gt; — Merge a branch into current branch</li><li>git branch -d &lt;name&gt; — Delete a branch</li></ul><h3>History and Information</h3><ul><li>git log — View commit history</li><li>git log --oneline — Compact history view</li><li>git log --graph --all — Visual branch history</li><li>git show &lt;commit&gt; — View commit details</li></ul><h3>Undoing Changes</h3><ul><li>git reset &lt;file&gt; — Unstage a file</li><li>git restore &lt;file&gt; — Discard working directory changes</li><li>git commit --amend — Modify the last commit</li><li>git revert &lt;commit&gt; — Create new commit that undoes changes</li></ul><h3>Remote Operations</h3><ul><li>git remote add origin &lt;url&gt; — Add a remote</li><li>git push origin &lt;branch&gt; — Push to remote</li><li>git pull origin &lt;branch&gt; — Pull from remote</li><li>git fetch — Download remote changes without merging</li></ul><h3>Best Practices</h3><ol><li><strong>Commit Often, Commit Early:</strong> Make small, frequent commits with clear messages</li><li><strong>Write Meaningful Commit Messages:</strong> Use present tense and be descriptive</li><li><strong>Use Branches:</strong> Keep main/master stable and develop features in branches</li><li><strong>Pull Before Push:</strong> Always pull the latest changes before pushing</li><li><strong>Review Before Committing:</strong> Use git diff and git status before committing</li><li><strong>Don’t Commit Sensitive Data:</strong> Use .gitignore for secrets and credentials</li><li><strong>Keep Commits Atomic:</strong> Each commit should represent one logical change</li></ol><h3>Common Workflows</h3><h3>Feature Branch Workflow</h3><pre>git checkout master<br>git pull origin master<br>git checkout -b feature-new-feature<br># Make changes<br>git add .<br>git commit -m &quot;Add new feature&quot;<br>git checkout master<br>git merge feature-new-feature<br>git push origin master</pre><h3>Fixing a Bug</h3><pre>git checkout -b bugfix-issue-123<br># Fix the bug<br>git add .<br>git commit -m &quot;Fix issue #123: Description of fix&quot;<br>git checkout master<br>git merge bugfix-issue-123</pre><h3>Conclusion</h3><p>Git is a powerful tool that becomes more intuitive with practice. This tutorial covered the essential commands you’ll use daily as a developer. The best way to master Git is to use it regularly in your projects.</p><p>Remember, Git is designed to be safe — most operations can be undone, so don’t be afraid to experiment. As you become more comfortable, explore advanced features like rebasing, cherry-picking, and interactive staging.</p><p>Happy coding, and may your commits always be clean!</p><h3>Additional Resources</h3><ul><li><a href="https://git-scm.com/doc">Official Git Documentation</a></li><li><a href="https://git-scm.com/book/en/v2">Pro Git Book</a> (Free)</li><li><a href="https://github.com/git-guides">GitHub Git Guides</a></li><li><a href="https://learngitbranching.js.org/">Interactive Git Learning</a></li></ul><p>You can see a live demo of this guide at this repository: <a href="https://github.com/nirmal-404/git-guide">https://github.com/nirmal-404/git-guide</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3351af223b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG Explained Simply: How LLMs Stop Guessing and Start Answering Correctly]]></title>
            <link>https://medium.com/@nirmalperera2509/rag-explained-simply-how-llms-stop-guessing-and-start-answering-correctly-298e0733ca67?source=rss-40963a346e5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/298e0733ca67</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[what-is-rag]]></category>
            <category><![CDATA[rag-architecture]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nirmal Perera]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 02:40:03 GMT</pubDate>
            <atom:updated>2025-12-30T02:40:03.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*yRylkAwhoyik12LCWgLyag.jpeg" /></figure><p>Large Language Models are impressive.<br> They’re also dangerously confident when they don’t know something.</p><p>That’s where <strong>RAG (Retrieval-Augmented Generation)</strong> comes in.</p><p>RAG changes how AI answers questions — replacing guesswork with <strong>retrieved, real knowledge</strong>.</p><h3>What Exactly Is RAG?</h3><p><strong>RAG stands for:</strong><br><strong>Retrieve → Augment → Generate</strong></p><p>Instead of asking an LLM to answer from memory alone, RAG forces it to:</p><ol><li>Retrieve relevant information</li><li>Inject that information into the prompt</li><li>Generate an answer grounded in that context</li></ol><p>Think of it as <strong>open-book AI</strong>, not closed-book guessing.</p><h3>Why Plain LLMs Fail</h3><p>A normal LLM pipeline looks like this:</p><pre>User Question → LLM → Answer (maybe correct, maybe nonsense</pre><p>LLMs don’t say <em>“I don’t know.”<br></em>They <strong>hallucinate confidently</strong>.</p><p>RAG fixes this by adding a retrieval step:</p><pre>User Question → Retriever → Relevant Knowledge → LLM → Answer</pre><p>Now the model answers using <strong>your data</strong>, not just its training.</p><h3>High-Level RAG Architecture</h3><p>Here’s the flow in simple terms:</p><ol><li><strong>User asks a question</strong></li><li>The question is converted into an embedding</li><li>A retriever finds the most relevant text chunks</li><li>Those chunks are added to the prompt</li><li>The LLM generates a concise answer</li></ol><p>No blind guessing. Just informed output.</p><h3>The Two Phases of RAG</h3><p>RAG systems operate in <strong>two distinct phases</strong>.</p><h3>1. Ingestion Phase (Building the Knowledge Base)</h3><p>This happens <strong>before users ask questions</strong>.</p><p><strong>Typical data sources</strong></p><ul><li>Documentation</li><li>FAQs</li><li>Blogs</li><li>PDFs</li><li>Internal wikis</li></ul><p><strong>Steps</strong></p><ul><li>Clean the data</li><li>Split it into chunks</li><li>Convert chunks into embeddings</li><li>Store them in a vector database</li></ul><p>This is a one-time (or periodic) process.</p><h3>2. Query Phase (Answering Questions)</h3><p>This runs <strong>every time a user asks something</strong>.</p><p><strong>Steps</strong></p><ul><li>Convert the user query into an embedding</li><li>Find similar chunks in the vector store</li><li>Build a prompt using those chunks</li><li>Generate the final answer with an LLM</li></ul><h3>Chunking: The Unsung Hero of RAG</h3><p>LLMs don’t understand entire documents at once.<br> They work best with <strong>small, meaningful pieces of text</strong>.</p><h3>Typical Chunking Strategy</h3><ul><li><strong>Chunk size:</strong> 500–1000 characters</li><li><strong>Overlap:</strong> 100–200 characters</li></ul><h3>Why Overlap Is Mandatory</h3><p>Without overlap, context is lost.</p><p>Example:</p><pre>Text: ABCDEFGH IJKLMN OPQRST</pre><pre>Chunk 1: ABCDEFGH<br>Chunk 2: IJKLMN</pre><p>Chunk 2 has no idea what came before.<br>With overlap:</p><pre>Chunk 1: ABCDEFGH<br>Chunk 2: GH IJKLMN<br>Chunk 3: MN OPQRST</pre><p>Now the model retains continuity across chunks.</p><h3>What Are Embeddings (Without the Math)?</h3><p><strong>An embedding is a numerical representation of meaning.</strong></p><ul><li>Text → Vector (list of numbers)</li><li>Similar meanings → closer vectors</li><li>Enables <strong>semantic search</strong>, not keyword matching</li></ul><p>This allows the system to find:</p><p><em>“What is conceptually similar?” </em>not just<em> “What contains the same words?”</em></p><h3>How Embeddings Power RAG</h3><ul><li>During ingestion → embed all text chunks</li><li>During query time → embed the user question</li><li>Compare vectors → retrieve the closest matches</li></ul><p>That’s how RAG finds <em>relevant</em> context.</p><h3>Vector Stores: Where Embeddings Live</h3><p>A <strong>vector store</strong> is a database designed for embeddings.</p><h3>What It Supports</h3><ul><li>Insert / update (upsert)</li><li>Similarity search</li><li>Metadata filtering</li></ul><h3>Typical Stored Data</h3><pre>{<br>  id,<br>  embedding,<br>  metadata: {<br>    source,<br>    page,<br>    section,<br>    tags<br>  }<br>}</pre><h3>Popular Choices</h3><ul><li>Supabase (pgvector)</li><li>MongoDB Vector Search</li><li>Pinecone</li><li>Weaviate</li><li>Qdrant</li></ul><p>Rule of thumb:</p><ul><li>Small projects → in-memory</li><li>Production → external vector database</li></ul><h3>The Real Value of RAG</h3><p>RAG turns LLMs from:</p><p><em>“confident guessers” </em>into: <em>“reliable knowledge workers”</em></p><p><strong>Benefits</strong></p><ul><li>Answers are grounded in real data</li><li>Hallucinations drop dramatically</li><li>Knowledge updates without retraining</li><li>Works with private and domain-specific data</li></ul><h3>Final Thoughts</h3><p>If you’re building AI that users must trust, <strong>RAG is not optional.</strong></p><p><strong>LLMs generate and RAG makes them answer correctly.</strong></p><h3>More From Me</h3><ul><li>GitHub → <a href="https://github.com/nirmal-404">github.com/nirmal-404</a></li><li>Portfolio → <a href="https://www.nirmalperera.me/">nirmalperera.me</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=298e0733ca67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why LangChain? A Practical Look Beyond Raw SDKs]]></title>
            <link>https://medium.com/@nirmalperera2509/why-langchain-a-practical-look-beyond-raw-sdks-424451811b61?source=rss-40963a346e5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/424451811b61</guid>
            <category><![CDATA[ai-prompts]]></category>
            <category><![CDATA[runnable]]></category>
            <category><![CDATA[ai-model]]></category>
            <category><![CDATA[output-parser]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Nirmal Perera]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 00:52:35 GMT</pubDate>
            <atom:updated>2025-12-06T01:02:34.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*GVE2S5Kt6UX0Nw9L_a6cIQ.png" /></figure><p>Large Language Models are powerful, but building directly on provider SDKs often feels like assembling machinery without tools. It works, but it’s repetitive, fragile, and becomes difficult to scale or maintain.</p><p><strong>LangChain addresses that gap.</strong></p><p>It provides a structured framework for integrating LLMs, handling the repetitive plumbing, and giving engineers the tools needed to build reliable AI systems at scale.</p><h3>Why LangChain Instead of Raw SDKs?</h3><p>Calling OpenAI, Gemini, Claude, or any other provider through their native SDKs is perfectly valid until your application grows. Then you end up writing and managing:</p><ul><li>repeating prompt code</li><li>manual response parsing</li><li>retry &amp; error handling logic</li><li>logging &amp; observability</li><li>migrating/switching models</li><li>your own RAG tooling</li></ul><p>In other words:</p><ul><li><strong>Raw SDKs = </strong>low-level control, high development cost</li><li><strong>LangChain = </strong>shared patterns, utilities, scalable workflows</li></ul><p>LangChain isn’t replacing SDKs, it’s elevating them into a maintainable ecosystem.</p><h3>Core Concepts of LangChain</h3><h3>1. Prompt</h3><p>A prompt in LC is more than text, it’s a <strong>template</strong> with:</p><ol><li>System role</li><li>Instructions</li><li>Variables/placeholders</li></ol><h4><strong>Why templates?</strong></h4><ul><li>Reusable</li><li>Predictable</li><li>Cleaner structure</li></ul><p>Good prompts = fewer hallucinations + consistent outputs.</p><h3>2. Model</h3><p>The model is the engine. LangChain acts as an abstraction layer on top, allowing you to switch providers without redesigning your application</p><p>Today it might be OpenAI, Tomorrow Claude or Gemini, Your architecture stays intact.</p><p>This separation gives future-proof flexibility.</p><h3>3. Output Parser</h3><p>LLMs return natural language, but applications need structure. Manually extracting JSON or fields from text is unreliable and brittle.</p><p>LangChain parsers let you enforce format and obtain structured output directly:</p><pre>Input → LLM → Output as JSON → ready to consume</pre><h3>Runnables : The Core Execution Model</h3><p>A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or transformed.</p><p>In LangChain, <strong>everything is a Runnable</strong> (a modular unit of work)</p><p>Think of it like Lego blocks.<br>Each block performs a task.<br>Chain the blocks and you’ll get a workflow.</p><h3>LCEL: LangChain Expression Language</h3><p>LCEL enables clean, chainable workflow composition. Similar in spirit to async/await for LLM operations.</p><h3>RunnableSequence</h3><p>Output of one step is the input of next step</p><pre>Prompt → Model → Parser → Final Data</pre><h3>RunnableMap</h3><p>Execute independent tasks simultaneously:</p><ul><li>One prompt generates title.</li><li>Another generates summary.</li><li>Another generates tags.</li><li>All at once. Fast.</li></ul><h3>Why should you care?</h3><p>Because real-world AI apps aren’t one-shot queries.</p><p>You’ll eventually want:</p><ul><li>RAG with vector stores</li><li>observability + logging</li><li>retries on model timeouts</li><li>output formatting</li><li>multi-model setups</li><li>workflows you can maintain</li></ul><p>LangChain gives you that <strong>without reinventing the wheel</strong>.</p><p>The toolkit grows with your app — and keeps your code sane.</p><h3>Final thought</h3><p>Raw SDKs are excellent for quick hacks.<br><strong>LangChain is what you use when you’re building something real.</strong></p><p>If you’re serious about AI applications, LC isn’t just convenient<br>it’s your foundation for scalable, maintainable workflows.</p><h3>More From Me</h3><ul><li>GitHub → <a href="https://github.com/nirmal-404">github.com/nirmal-404</a></li><li>Portfolio → <a href="https://www.nirmalperera.me/">nirmalperera.me</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=424451811b61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering AI Model Controls: Tokens, Temperature, Tools & Structured Output]]></title>
            <link>https://medium.com/@nirmalperera2509/mastering-ai-model-controls-tokens-temperature-tools-structured-output-174d5df0071a?source=rss-40963a346e5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/174d5df0071a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[structured-output]]></category>
            <category><![CDATA[ai-model-controls]]></category>
            <category><![CDATA[ai-model]]></category>
            <dc:creator><![CDATA[Nirmal Perera]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 22:21:10 GMT</pubDate>
            <atom:updated>2025-12-06T01:02:54.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeGWPLWXgnQZQaAE-b8Jmw.jpeg" /></figure><p>Modern LLMs are powerful, but if you don’t understand the dials, you’ll burn tokens, money, and sanity. This guide cuts the fluff and tells you exactly how to control models like OpenAI, Gemini, and Ollama for predictable, efficient results.</p><h3>Tokens &amp; Context Window — The Real Cost of “Just One More Message”</h3><p><strong>Tokens</strong> are chunks of text the model reads or writes. More tokens = more cost, more latency, and more chances for things to break.</p><p><strong>Context window</strong> = everything the model can “see” at once:</p><ul><li>system instructions</li><li>your prompt</li><li>chat history</li><li>tool responses</li><li>the model’s own previous output</li></ul><p>If you overload it, the model starts <strong>truncating</strong> history. Translation: something disappears, and your output starts acting weird.</p><p><strong>Rules of survival:</strong></p><ul><li>Short prompts beat long essays.</li><li>Concise beats clever rambling.</li><li>Every extra token costs money.</li><li>Long outputs = even more tokens = more cost.</li></ul><h3>Temperature, Top-P, Max Tokens &amp; Penalties — The Model’s Control Panel</h3><h3>Temperature</h3><p>Controls the <em>stability vs creativity</em> trade-off.</p><p>TemperatureBehavior<strong>0–0.2</strong>Safe, boring, deterministic. Best for structured formats (JSON).<strong>0.3–0.7</strong>More creative. Can drift from strict formats.<strong>&gt; 0.7</strong>Wild west. Fun for brainstorming, terrible for precision.</p><h3>Top-P</h3><p>Controls “how wide” the model samples from possible words.</p><ul><li><strong>1.0</strong> — consider all likely words (default)</li><li><strong>0.9</strong> — ignore the long-tail words; stabilizes JSON output</li></ul><p><strong>Beginner rule:</strong><br> <strong>Tune <em>either</em> temperature OR top_p, not both.</strong></p><p>Most broken JSON comes from:</p><ul><li>high temperature</li><li>tiny max_tokens</li></ul><h3>Max Tokens</h3><p>Hard cap on response length.</p><ul><li>Too small → truncated JSON, unfinished sentences</li><li>Good baseline for structured tasks (summary, confidence, etc.) → <strong>256</strong></li></ul><h3>Penalties</h3><p>Keep repetition down. Useful for long text generation, not needed for short JSON tasks.</p><h3>Mapping Parameters: OpenAI vs Gemini vs Ollama</h3><p>ConceptOpenAIGeminiOllamaTemperaturetemperaturegenerationConfig.temperatureoptions.temperatureTop-Ptop_pgenerationConfig.topPoptions.top_pMax Tokensmax_tokensgenerationConfig.maxOutputTokensoptions.num_predict</p><p>Different names. Same idea. Don’t overthink it.</p><h3>Chat Models vs Tool-Enabled Models</h3><h3>Chat Models</h3><p>Best for:</p><ul><li>free-form answers</li><li>explanations</li><li>compact JSON</li><li>tasks that don’t need external APIs or browsing</li></ul><p><strong>BUT</strong>:<br> They may <em>not</em> follow strict formats 100% of the time.</p><h3>Tool Models</h3><p>Best for:</p><ul><li>browsing, API calls, file access</li><li>tasks where the model must gather external info</li><li>function-calling workflows</li></ul><p>The model can:</p><ol><li>Plan</li><li>Pick a tool</li><li>Execute</li><li>Observe</li><li>Decide next steps</li></ol><p>This loop is reliable when you need real data, not guesses.</p><h3>Structured Output with Zod — Your Contract With the Model</h3><p>Zod defines the exact shape of output you expect.<br> The same schema works for both runtime validation and TypeScript typing neat.</p><pre>import { z } from &#39;zod&#39;<br><br>export const JsonResponseSchema = z.object({<br>  summary: z.string(),<br>  confidence: z.number()<br>})<br>export type JsonResponse = z.infer&lt;typeof JsonResponseSchema&gt;</pre><h3>Why schemas matter</h3><ul><li>More reliable than “please respond in JSON”</li><li>Validates at runtime</li><li>Catches malformed output early</li><li>Plays nicely with OpenAI, Gemini, and other providers</li></ul><h3>Structured Output Mode</h3><p>Ask the model to <em>fill a schema</em>, not to <em>guess the format</em>.<br> Modern LLM APIs provide:</p><ul><li>JSON-only mode</li><li>Strict schema-filled mode</li><li>Tool-calling mode</li></ul><p>When you combine:<br> <strong>schema → structured mode → validator</strong>,<br> the JSON becomes predictable and boring — exactly what you want.</p><h3>When to Choose What</h3><h3>Choose Chat Model when:</h3><ul><li>Writing explanations, summaries, essays</li><li>Producing simple JSON</li><li>You don’t need browsing or external tools</li></ul><h3>Choose Tool Model when:</h3><ul><li>You need to fetch URLs, search the web, or read files</li><li>You want the model to plan + use tools automatically</li><li>Workflow: <strong>plan → tool → observe → iterate</strong></li></ul><h3>Final Thoughts</h3><p>Controlling an LLM is like driving a performance car.<br>Most people slam all the buttons and pray.<br>You won’t.</p><p>If you understand:</p><ul><li>tokens</li><li>temperature</li><li>top_p</li><li>max_tokens</li><li>structured output</li><li>tools vs chat</li></ul><p>…you’ll get predictable, cheap, and high-quality results every time.</p><h3>More From Me</h3><ul><li>GitHub → <a href="https://github.com/nirmal-404">github.com/nirmal-404</a></li><li>Portfolio → <a href="https://www.nirmalperera.me/">nirmalperera.me</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=174d5df0071a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your AI App Needs Structured Outputs: The JSON-First Mindset]]></title>
            <link>https://medium.com/@nirmalperera2509/why-your-ai-app-needs-structured-outputs-the-json-first-mindset-f260bb651a20?source=rss-40963a346e5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f260bb651a20</guid>
            <category><![CDATA[structured-output]]></category>
            <category><![CDATA[json-schema]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[zod-validation]]></category>
            <category><![CDATA[llm-reliability]]></category>
            <dc:creator><![CDATA[Nirmal Perera]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 21:57:43 GMT</pubDate>
            <atom:updated>2025-12-06T01:01:24.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*34AoqXg7DsUf_f35WLVuqQ.jpeg" /></figure><p>Let me tell you about a mistake I see constantly in AI applications devloped by beginners, and one that I’ve definitely made myself: treating LLM outputs as paragraphs instead of data.</p><p>It seems harmless at first. Your app works in testing. But then it breaks in production in ways that are almost impossible to debug. Let me explain why, and how to fix it.</p><h3>The Problem with Paragraph Outputs</h3><p>Here’s what most people do when they start building with LLMs:</p><pre>Prompt: &quot;Analyze this customer review and tell me the sentiment&quot;<br>   ↓<br>LLM Response: &quot;Based on my analysis of this review, <br>I would say the sentiment is quite positive. The customer <br>seems happy with the product, though they did mention <br>some minor concerns about shipping time...&quot;</pre><p>Looks fine, right? Now try to use this in your app:</p><ul><li>How do you extract the sentiment? String parsing?</li><li>What if tomorrow the LLM says “The sentiment leans positive” instead of “quite positive”?</li><li>How do you handle this in your UI?</li><li>How do you test this reliably?</li><li>What happens when the LLM adds extra commentary you didn’t ask for?</li></ul><p><strong>The answer: your app breaks, and you can’t even write a test to catch it.</strong></p><h3>The JSON-First Mindset</h3><p>Here’s the core principle: <strong>treat LLM output as data, not paragraphs</strong>.</p><p>Instead of getting a paragraph, ask for JSON:</p><pre>Prompt: &quot;Analyze this customer review and return JSON <br>with sentiment (positive/neutral/negative) and confidence (0-1)&quot;<br>↓<br>LLM Response:<br>{<br>  &quot;sentiment&quot;: &quot;positive&quot;,<br>  &quot;confidence&quot;: 0.85,<br>}</pre><p>Now look at what you gain:</p><ul><li><strong>Predictable structure: </strong>You know exactly what fields you’ll get</li><li><strong>Type safety: </strong>Frontend knows it’s getting an object with specific properties</li><li><strong>Testable: </strong>You can write actual unit tests</li><li><strong>Parseable: </strong>No string manipulation needed</li><li><strong>Composable: </strong>Easy to pass to other functions or store in a database</li></ul><h3>Why This Matters for Production Apps</h3><p>Let’s trace through what happens with paragraph outputs in a real application:</p><ol><li><strong>Development: </strong>Works fine in your tests with the handful of examples you tried</li><li><strong>Staging: </strong>Mostly works, occasional weird formatting</li><li><strong>Production: </strong>Your frontend breaks because:</li></ol><ul><li>LLM suddenly adds markdown formatting</li><li>Extra sentences you didn’t expect</li><li>Slightly different phrasing breaks your regex</li><li>Missing information you assumed would be there</li></ul><p>4.Now you’re stuck trying to handle every possible variation of human-like text. It’s a nightmare.</p><p><strong>5. With JSON, the contract is clear.</strong> Either you get valid JSON matching your schema, or you get an error. No ambiguity. No silent failures.</p><h3>Enforcing Structure with Schema Validation</h3><p>Getting JSON from an LLM isn’t enough. You need to <strong>enforce the shape</strong> of that JSON.</p><p>This is where schema validation comes in. Tools like <strong>Zod</strong> (for TypeScript) let you define exactly what structure you expect:</p><pre>import { z } from &#39;zod&#39;;<br><br>const SentimentSchema = z.object({<br>  sentiment: z.enum([&#39;positive&#39;, &#39;neutral&#39;, &#39;negative&#39;]),<br>  confidence: z.number().min(0).max(1),<br>  key_points: z.array(z.string()),<br>  summary: z.string().optional()<br>});<br>type Sentiment = z.infer&lt;typeof SentimentSchema&gt;;</pre><p>Now when your LLM returns data, you validate it:</p><pre>const llmOutput = await getLLMResponse(prompt);<br>const parsed = JSON.parse(llmOutput);<br>const validated = SentimentSchema.parse(parsed);<br>// If we get here, we KNOW the data matches our schematy</pre><p><strong>What this gives you:</strong></p><ol><li><strong>Compile-time safety: </strong>TypeScript knows the exact shape</li><li><strong>Runtime validation: </strong>Catches malformed outputs immediately</li><li><strong>Self-documenting: </strong>The schema is your API contract</li><li><strong>Refactoring confidence: </strong>Change the schema, TypeScript shows you what breaks</li></ol><h3>Real-World Example: Before and After</h3><h3>Before (Paragraph Outputs)</h3><pre>const prompt = &quot;List 3 product recommendations&quot;;<br>const response = await openai.complete(prompt);<br>// response: &quot;Here are my recommendations: <br>// 1. iPhone 15 - great camera<br>// 2. Samsung Galaxy - good value<br>// ...&quot;<br>// Now what? Parse with regex? Hope the format never changes?<br>// How do you handle this in your UI?<br>// What if it returns 2 items instead of 3?</pre><p><strong>Testing this?</strong> Nearly impossible. You’d have to check if the string contains certain phrases. Fragile and unreliable.</p><h3>After (JSON-First)</h3><pre>const ProductSchema = z.object({<br>  recommendations: z.array(z.object({<br>    name: z.string(),<br>    reason: z.string(),<br>    price: z.number().optional()<br>  })).length(3)<br>});</pre><pre>const prompt = `List 3 product recommendations. <br>Return ONLY valid JSON matching this schema: ${JSON.stringify(ProductSchema)}`;<br>const response = await openai.complete(prompt);<br>const data = ProductSchema.parse(JSON.parse(response));<br>// Now you have:<br>// data.recommendations[0].name<br>// data.recommendations[0].reason<br>// Fully typed, fully validated</pre><p><strong>Testing this?</strong> Easy:</p><p>typescript</p><pre>test(&#39;returns 3 recommendations with required fields&#39;, () =&gt; {<br>  const result: Product = ProductSchema.parse(mockLLMOutput);<br>  <br>  expect(result.recommendations).toHaveLength(3);<br><br>  const first = result.recommendations[0];<br>  expect(first).toHaveProperty(&#39;name&#39;);<br>  expect(first.name).toBeDefined();<br>  expect(first).toHaveProperty(&#39;reason&#39;);<br>  expect(first.reason).toBeDefined();<br>});</pre><h3>How to Prompt for JSON</h3><p>Getting LLMs to return valid JSON consistently requires specific prompting:</p><p><strong>Key techniques:</strong></p><ol><li><strong>Be explicit</strong> — “Return ONLY valid JSON, no other text”</li><li><strong>Show the schema</strong> — Include the Zod schema or a JSON example</li><li><strong>Use system messages</strong> — Many APIs let you set a system message that enforces JSON mode</li><li><strong>Validate and retry</strong> — If parsing fails, retry with a clarifying prompt</li></ol><p><strong>Example prompt:</strong></p><pre>You are a data extraction assistant. ONLY return valid JSON. No explanations, no extra text.  <br><br>Extract sentiment from this review and return a JSON object with the following structure:<br>{<br>  &quot;sentiment&quot;: &quot;positive&quot; | &quot;neutral&quot; | &quot;negative&quot;,<br>  &quot;confidence&quot;: number,  // between 0 and 1<br>  &quot;key_points&quot;: string[]<br>}<br><br>Review: &quot;Great product but shipping was slow&quot;<br><br>Return ONLY the JSON object.</pre><h3>The Testing Advantage</h3><p>This is where JSON-first really shines. Consider these scenarios:</p><p><strong>Paragraph output:</strong></p><ul><li>How do you test that the LLM “sounds professional”?</li><li>How do you test that it “includes relevant information”?</li><li>How do you test that it “formats nicely”?</li></ul><p>You can’t. Not reliably.</p><p><strong>JSON output:</strong></p><ul><li>Does the schema match?</li><li>Are required fields present?</li><li>Are values in valid ranges?</li><li>Is the data type correct?</li></ul><p>These are <strong>objective, binary tests</strong>. They either pass or fail. No ambiguity.</p><h3>When Paragraphs Are Fine</h3><p>To be fair, there are times when you want natural language output:</p><ul><li>Chatbots where the final output is shown to users as-is</li><li>Content generation where formatting matters (blog posts, emails)</li><li>Creative writing</li></ul><p>But even then, consider wrapping the paragraph in JSON:</p><p>json</p><pre>{<br>  &quot;content&quot;: &quot;Your natural language paragraph here...&quot;,<br>  &quot;metadata&quot;: {<br>    &quot;tone&quot;: &quot;professional&quot;,<br>    &quot;word_count&quot;: 150<br>  }<br>}</pre><p>This gives you the paragraph you need plus structured data about it.</p><h3>Practical Implementation Tips</h3><p><strong>1. Start with strict schemas, relax later</strong> Better to be too strict and loosen up than deal with unpredictable data.</p><p><strong>2. Use optional fields strategically</strong> Don’t make everything required, but don’t make everything optional either.</p><p><strong>3. Provide good error messages</strong> When validation fails, tell the LLM what went wrong and let it retry.</p><p><strong>4. Test with real data</strong> Don’t just test happy paths. Test with weird inputs and edge cases.</p><h3>The Bottom Line</h3><p>When you get a prompt as a paragraph, it’s nearly impossible to test. You don’t know what you’re going to get, so your frontend breaks in unpredictable ways.</p><p><strong>JSON makes LLM outputs:</strong></p><ul><li>Predictable</li><li>Testable</li><li>Integrable</li><li>Debuggable</li><li>Type-safe</li></ul><p>It transforms LLM responses from “hope this works” to “guaranteed contract.”</p><p><strong>Start thinking of LLMs as APIs that return structured data, not as chatbots that return text.</strong> This single mindset shift will save you countless hours of debugging and make your AI applications actually reliable in production.</p><p><strong>Quick win:</strong> Take one LLM call in your app that returns a paragraph. Rewrite the prompt to request JSON. Add Zod validation. Watch your confidence in that feature grow.</p><p>That’s the power of the JSON-first mindset.</p><h3>More From Me</h3><ul><li>GitHub → <a href="https://github.com/nirmal-404">github.com/nirmal-404</a></li><li>Portfolio → <a href="https://www.nirmalperera.me/">nirmalperera.me</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f260bb651a20" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>