<?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"><channel><title><![CDATA[Zen of Daily Code]]></title><description><![CDATA[A personal record of small tech experiments and ideas from daily life.
Most posts are English versions of articles originally written in Japanese on zenn.dev.]]></description><link>https://ara-ta3.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1747624125367/d366bb4c-6116-4787-b8a2-0709d78dbda5.png</url><title>Zen of Daily Code</title><link>https://ara-ta3.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 10 Nov 2026 09:18:59 GMT</lastBuildDate><atom:link href="https://ara-ta3.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Load a .env File into a Go Struct with Viper]]></title><description><![CDATA[Read a .env file in Go with Viper and decode its values into a struct using mapstructure tags.]]></description><link>https://ara-ta3.hashnode.dev/how-to-load-a-env-file-into-a-go-struct-with-viper</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/how-to-load-a-env-file-into-a-go-struct-with-viper</guid><category><![CDATA[Go Language]]></category><category><![CDATA[Viper]]></category><category><![CDATA[configuration]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Thu, 15 Oct 2026 07:20:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/682a9372fe5ea4247ff9c37e/2236e9de-1782-427d-9dbd-2cfe5200086e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>When I came back to Go, I wanted to load a small configuration file into a struct. I found <a href="https://github.com/spf13/viper">Viper</a> while browsing awesome-go and tried it with an env-format file.</p>
<p>This example reads a <code>.env</code> file, maps its keys to struct fields, and prints the result. It is an English adaptation of my <a href="https://zenn.dev/ara_ta3/articles/golang-viper-reading-env">Japanese article on Zenn</a>.</p>
<h2>Set up the project</h2>
<pre><code class="language-bash">mkdir viper-env-example
cd viper-env-example
go mod init example.com/viper-env-example
go get github.com/spf13/viper
</code></pre>
<p>The project will contain:</p>
<pre><code class="language-text">viper-env-example/
├── .env
├── go.mod
├── go.sum
└── main.go
</code></pre>
<p>Create <code>.env</code> with a few sample values:</p>
<pre><code class="language-dotenv">XXX=a
YYY=b
ZZZ=c
</code></pre>
<p>These are sample values. Keep real credentials out of version control.</p>
<h2>Read the file and unmarshal it into a struct</h2>
<p>Create <code>main.go</code>:</p>
<pre><code class="language-go">package main

import (
    "fmt"

    "github.com/spf13/viper"
)

type EnvConfigs struct {
    X string `mapstructure:"XXX"`
    Y string `mapstructure:"YYY"`
}

func Load() (EnvConfigs, error) {
    config := viper.New()
    config.SetConfigFile(".env")
    config.SetConfigType("env")

    if err := config.ReadInConfig(); err != nil {
        return EnvConfigs{}, err
    }

    var result EnvConfigs
    if err := config.Unmarshal(&amp;result); err != nil {
        return EnvConfigs{}, err
    }
    return result, nil
}

func main() {
    config, err := Load()
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", config)
}
</code></pre>
<p><code>SetConfigFile(".env")</code> selects the file explicitly, relative to the process's working directory. <code>SetConfigType("env")</code> specifies the parser. <code>ReadInConfig()</code> reads the file, and <code>Unmarshal()</code> decodes the values into <code>EnvConfigs</code>.</p>
<p>The <code>mapstructure</code> tags map <code>XXX</code> to <code>X</code> and <code>YYY</code> to <code>Y</code>. There is no field for <code>ZZZ</code>, so that value does not appear in the result.</p>
<p>I used <code>viper.New()</code> here to keep the configuration local to this loader, rather than using the package-level instance from the original experiment.</p>
<h2>Run the example</h2>
<p>From the directory containing <code>.env</code>:</p>
<pre><code class="language-bash">go run .
</code></pre>
<p>Expected output:</p>
<pre><code class="language-text">{X:a Y:b}
</code></pre>
<p>If the file is missing, <code>Load()</code> returns an error. The example does not silently replace a missing file with an empty configuration.</p>
<h2>A .env file is different from process environment variables</h2>
<p>This example reads a file as configuration. It does not export those values into the process environment, and it does not call <code>AutomaticEnv()</code> to read environment variables.</p>
<p>If you also want process environment variables to override file values, configure that separately. When decoding into a struct, explicitly binding the relevant keys with <code>BindEnv()</code> helps make the keys available to Viper; do not assume that calling <code>AutomaticEnv()</code> alone discovers every environment variable for <code>Unmarshal()</code>.</p>
<p>For this small example, reading the file alone is enough.</p>
<h2>Summary</h2>
<p>Viper can read an env-format file and decode it into a Go struct using <code>mapstructure</code> tags. The key steps are selecting the file, setting its format, calling <code>ReadInConfig()</code>, and then calling <code>Unmarshal()</code>.</p>
<p>The original experiment used a file named <code>dot_env_file</code>; selecting <code>.env</code> explicitly makes this version easier to reuse in a typical project.</p>
<h2>References</h2>
<ul>
<li><a href="https://github.com/spf13/viper#reading-config-files">Viper: Reading Config Files</a></li>
<li><a href="https://github.com/spf13/viper#working-with-environment-variables">Viper: Working with Environment Variables</a></li>
<li><a href="https://github.com/spf13/viper#unmarshaling">Viper: Unmarshaling</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Build a Todo App with Scala.js, React, and Vite]]></title><description><![CDATA[Build a Todo app with Scala.js, React, and Vite. Follow the Scala-to-JavaScript build flow and add typed Tailwind CSS classes with ScalaWind.]]></description><link>https://ara-ta3.hashnode.dev/build-a-todo-app-with-scala-js-react-and-vite</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/build-a-todo-app-with-scala-js-react-and-vite</guid><category><![CDATA[Scala]]></category><category><![CDATA[scalajs]]></category><category><![CDATA[React]]></category><category><![CDATA[vite]]></category><category><![CDATA[Tailwind CSS]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Thu, 15 Oct 2026 07:18:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/682a9372fe5ea4247ff9c37e/3830503e-439f-479f-a027-cb9b1d5b20f9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>I first tried Scala.js with Vue.js years ago. Recently, I revisited it and found that the ecosystem also has React bindings and ScalaWind for writing Tailwind classes through a typed Scala API.</p>
<p>This article follows how a small Todo application reaches the browser: Scala becomes JavaScript, Vite serves it, and React renders the page. The application supports adding, completing, and deleting tasks.</p>
<p>It is an English adaptation of my <a href="https://zenn.dev/ara_ta3/articles/scalajs-react-vite-getting-started">Japanese article on Zenn</a>.</p>
<p>The <a href="https://github.com/ara-ta3/zlab-scalajs-react-getting-started/tree/174a50dc24023f1cdda8024fddd8e68429760393">public sample</a> uses plain CSS. I'll use that reproducible baseline first, then add the Tailwind/ScalaWind integration from the Japanese article. The versions below reflect this checked configuration rather than every version listed in the original article.</p>
<h2>What each tool does</h2>
<table>
<thead>
<tr>
<th>Tool</th>
<th>Role</th>
</tr>
</thead>
<tbody><tr>
<td>Scala.js</td>
<td>Compiles and links Scala into JavaScript</td>
</tr>
<tr>
<td>scalajs-react</td>
<td>Exposes React APIs to Scala code</td>
</tr>
<tr>
<td>sbt</td>
<td>Manages Scala dependencies and the Scala.js build</td>
</tr>
<tr>
<td>npm</td>
<td>Manages React, Vite, and the CSS tooling</td>
</tr>
<tr>
<td>Vite</td>
<td>Serves and bundles the browser assets</td>
</tr>
<tr>
<td>Tailwind CSS</td>
<td>Generates CSS for utility classes, in the optional extension</td>
</tr>
<tr>
<td>ScalaWind</td>
<td>Generates a typed Scala API for Tailwind classes</td>
</tr>
</tbody></table>
<pre><code class="language-text">Scala source -&gt; sbt / Scala.js -&gt; JavaScript -&gt; Vite -&gt; browser
                                                        |
                                         React renders the DOM
</code></pre>
<p>Vite does not compile Scala directly. Its Scala.js plugin connects it to sbt's output. The React implementation itself comes from npm; scalajs-react is the Scala-facing layer.</p>
<h2>Run the complete baseline</h2>
<p>Install a JDK, sbt, and Node.js. This example uses Scala 3.3.3, sbt 1.10.11, Scala.js 1.22.0, scalajs-react 4.0.0, React 19.1.1, and Vite 7.3.6. The build was checked with Node.js 24.</p>
<pre><code class="language-bash">git clone https://github.com/ara-ta3/zlab-scalajs-react-getting-started.git
cd zlab-scalajs-react-getting-started
git checkout 174a50dc24023f1cdda8024fddd8e68429760393
npm ci
npm run dev
</code></pre>
<p>Open the local URL printed by Vite, usually <code>http://localhost:5173</code>. The checked-out sample has Japanese task labels; the snippets below translate them into English.</p>
<p>The important files are:</p>
<pre><code class="language-text">build.sbt
project/plugins.sbt
project/build.properties
package.json
index.html
main.js
style.css
vite.config.js
src/main/scala/todo/
  Main.scala
  domain/Todo.scala
  pages/TodoPage.scala
  components/TodoForm.scala
  components/TodoList.scala
</code></pre>
<h2>Connect the HTML entry point to Scala.js</h2>
<p>The browser starts with <code>index.html</code>:</p>
<pre><code class="language-html">&lt;!doctype html&gt;
&lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;meta charset="UTF-8" /&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;
    &lt;title&gt;Scala.js TODO&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id="app"&gt;&lt;/div&gt;
    &lt;script type="module" src="/main.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>React will render into <code>#app</code>. The module entry point, <code>main.js</code>, imports the stylesheet and Scala.js module:</p>
<pre><code class="language-javascript">import "./style.css";
import "scalajs:main.js";
</code></pre>
<p><code>scalajs:main.js</code> is resolved by the Vite plugin configured in <code>vite.config.js</code>:</p>
<pre><code class="language-javascript">import { defineConfig } from "vite";
import scalaJSPlugin from "@scala-js/vite-plugin-scalajs";

export default defineConfig({
  plugins: [scalaJSPlugin()],
});
</code></pre>
<h2>Configure sbt and Scala.js</h2>
<p>In <code>project/plugins.sbt</code>, enable the Scala.js plugin:</p>
<pre><code class="language-scala">addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.22.0")
</code></pre>
<p>In <code>project/build.properties</code>, select sbt:</p>
<pre><code class="language-text">sbt.version=1.10.11
</code></pre>
<p>The application's <code>build.sbt</code> configures Scala, the JavaScript module format, and its Scala dependencies:</p>
<pre><code class="language-scala">import org.scalajs.linker.interface.{ModuleKind, ModuleSplitStyle}

lazy val todoApp = project
  .in(file("."))
  .enablePlugins(ScalaJSPlugin)
  .settings(
    scalaVersion := "3.3.3",
    scalaJSUseMainModuleInitializer := true,
    scalaJSLinkerConfig ~= {
      _.withModuleKind(ModuleKind.ESModule)
        .withModuleSplitStyle(ModuleSplitStyle.SmallModulesFor(List("todo")))
    },
    libraryDependencies ++= Seq(
      "org.scala-js" %%% "scalajs-dom" % "2.8.1",
      "com.github.japgolly.scalajs-react" %%% "core" % "4.0.0"
    )
  )
</code></pre>
<p><code>scalaJSUseMainModuleInitializer := true</code> runs the Scala <code>main</code> method when the generated module loads. ES modules let Vite handle the linked JavaScript as modules.</p>
<p>The <code>%%%</code> dependency notation selects Scala.js artifacts. It does not install npm's React package; that dependency is managed separately in <code>package.json</code>.</p>
<h2>Render the Todo application</h2>
<p><code>Main.scala</code> connects the Scala component to the React root:</p>
<pre><code class="language-scala">package todo

import japgolly.scalajs.react.ReactDOMClient
import org.scalajs.dom
import todo.pages.TodoPage

object Main {
  def main(args: Array[String]): Unit = {
    ReactDOMClient.createRoot(dom.document.getElementById("app")).render(TodoPage())
  }
}
</code></pre>
<p>The domain value, in <code>domain/Todo.scala</code>, uses <code>Todo.Id</code> to distinguish a task ID from an arbitrary integer:</p>
<pre><code class="language-scala">package todo.domain

final case class Todo(id: Todo.Id, title: String, isDone: Boolean)

object Todo {
  final case class Id(value: Int)
}
</code></pre>
<p><code>pages/TodoPage.scala</code> owns the input text, the list, and the operations:</p>
<pre><code class="language-scala">package todo.pages

import japgolly.scalajs.react.*
import japgolly.scalajs.react.vdom.html_&lt;^.*
import todo.components.{TodoForm, TodoList}
import todo.domain.Todo

object TodoPage {
  private val initialTodos = Vector(
    Todo(Todo.Id(1), "Try Scala.js", false),
    Todo(Todo.Id(2), "Write an article", false),
    Todo(Todo.Id(3), "Read about React", true)
  )

  private val Component = ScalaFnComponent.withHooks[Unit]
    .useState("")
    .useState(initialTodos)
    .render((_, title, todos) =&gt; {
      def addTodo: Callback = {
        val trimmedTitle = title.value.trim

        if (trimmedTitle.isEmpty) {
          Callback.empty
        } else {
          todos.modState { items =&gt;
            val nextId = items.map(_.id.value).maxOption.getOrElse(0) + 1
            items :+ Todo(Todo.Id(nextId), trimmedTitle, false)
          } &gt;&gt; title.setState("")
        }
      }

      def toggleTodo(todoId: Todo.Id): Callback = {
        todos.modState(_.map { todo =&gt;
          if (todo.id == todoId) todo.copy(isDone = !todo.isDone)
          else todo
        })
      }

      def deleteTodo(todoId: Todo.Id): Callback = {
        todos.modState(_.filterNot(_.id == todoId))
      }

      &lt;.main(^.className := "todo-app",
        &lt;.h1("TODO"),
        TodoForm(TodoForm.Props(title.value, title.setState, addTodo)),
        TodoList(TodoList.Props(todos.value, toggleTodo, deleteTodo))
      )
    })

  def apply() = Component()
}
</code></pre>
<p><code>useState</code> keeps the input and list state. <code>Callback</code> represents the effects passed into React's event handlers. <code>modState</code> updates the list from its previous value.</p>
<p><code>components/TodoForm.scala</code> receives its value and callbacks as props:</p>
<pre><code class="language-scala">package todo.components

import japgolly.scalajs.react.*
import japgolly.scalajs.react.vdom.html_&lt;^.*
import org.scalajs.dom

object TodoForm {
  final case class Props(value: String, onChange: String =&gt; Callback, onSubmit: Callback)

  private val Component = ScalaFnComponent[Props] { props =&gt;
    &lt;.form(
      ^.className := "todo-form",
      ^.onSubmit ==&gt; (_.preventDefaultCB &gt;&gt; props.onSubmit),
      &lt;.input(
        ^.value := props.value,
        ^.onChange ==&gt; { event =&gt;
          props.onChange(event.target.asInstanceOf[dom.HTMLInputElement].value)
        },
        ^.placeholder := "Enter a task"
      ),
      &lt;.button(^.`type` := "submit", "Add")
    )
  }

  def apply(props: Props) = Component(props)
}
</code></pre>
<p>The form prevents the browser's default submit behavior and runs the callback supplied by the page.</p>
<p><code>components/TodoList.scala</code> renders the list and passes task IDs back to the page:</p>
<pre><code class="language-scala">package todo.components

import japgolly.scalajs.react.*
import japgolly.scalajs.react.vdom.html_&lt;^.*
import todo.domain.Todo

object TodoList {
  final case class Props(
    todos: Vector[Todo],
    onToggle: Todo.Id =&gt; Callback,
    onDelete: Todo.Id =&gt; Callback
  )

  private val Component = ScalaFnComponent[Props] { props =&gt;
    &lt;.ul(^.className := "todo-list",
      props.todos.map { todo =&gt;
        &lt;.li(^.key := todo.id.value.toString, ^.className := "todo-item",
          &lt;.label(^.className := "todo-label",
            &lt;.input.checkbox(
              ^.checked := todo.isDone,
              ^.onChange --&gt; props.onToggle(todo.id)
            ),
            &lt;.span(^.classSet("is-done" -&gt; todo.isDone), todo.title)
          ),
          &lt;.button(
            ^.className := "delete-button",
            ^.onClick --&gt; props.onDelete(todo.id),
            "Delete"
          )
        )
      }.toVdomArray
    )
  }

  def apply(props: Props) = Component(props)
}
</code></pre>
<p>The application keeps its state in memory. Refreshing the page resets the tasks; there is no backend or persistent storage in this example. The complete baseline stylesheet is in the linked sample's <code>style.css</code>.</p>
<h2>Add Tailwind CSS and ScalaWind</h2>
<p>The Japanese article also explores typed Tailwind classes. This extension keeps the baseline app and its existing CSS, adding a typed class expression to the heading.</p>
<p>The configuration below uses Tailwind CSS 3's PostCSS integration. It is not a Tailwind CSS 4 setup. ScalaWind 1.0.4 is used here because the version listed in the original article could not be retrieved during verification.</p>
<p>Install the extension's packages:</p>
<pre><code class="language-bash">npm install --save-dev --save-exact scalawind@1.0.4 tailwindcss@3.4.17 postcss@8.5.30 autoprefixer@10.6.1
</code></pre>
<p>Create <code>postcss.config.js</code>:</p>
<pre><code class="language-javascript">export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};
</code></pre>
<p>Create <code>tailwind.config.cjs</code>:</p>
<pre><code class="language-javascript">const { scalaSourceTransform } = require("scalawind/dist/transform");

module.exports = {
  content: {
    files: [
      "./index.html",
      "./src/main/scala/todo/Main.scala",
      "./src/main/scala/todo/components/**/*.scala",
      "./src/main/scala/todo/domain/**/*.scala",
      "./src/main/scala/todo/pages/**/*.scala",
    ],
    transform: scalaSourceTransform,
  },
};
</code></pre>
<p>The generated ScalaWind source is deliberately excluded from the scanned paths. Scanning its full generated API would include utility classes the application does not use.</p>
<p>Prepend these directives to the existing <code>style.css</code>, keeping the baseline rules below them:</p>
<pre><code class="language-css">@tailwind base;
@tailwind components;
@tailwind utilities;
</code></pre>
<p>Register the generator and run it:</p>
<pre><code class="language-bash">npm pkg set 'scripts.postinstall=scalawind generate --check-duplication --check-optimization -f scalajs-react -o ./src/main/scala/todo/scalawind.scala -p todo'
npm run postinstall
</code></pre>
<p>Add <code>src/main/scala/todo/scalawind.scala</code> to <code>.gitignore</code>. Subsequent installs can regenerate the file through <code>postinstall</code> after the Tailwind configuration exists.</p>
<p>In <code>TodoPage.scala</code>, add this import:</p>
<pre><code class="language-scala">import todo.*
</code></pre>
<p>Then replace <code>&lt;.h1("TODO")</code> with:</p>
<pre><code class="language-scala">&lt;.h1(^.className := tw.text_3xl.font_bold.text_slate_800.css, "TODO")
</code></pre>
<p>ScalaWind generates the typed <code>tw</code> API. The expression produces <code>text-3xl font-bold text-slate-800</code>; Tailwind generates the corresponding CSS. ScalaWind generates Scala code, while Tailwind generates CSS, so both parts are needed.</p>
<h2>Build for production</h2>
<pre><code class="language-bash">npm run build
npm run preview
</code></pre>
<p>The Vite plugin connects the production build to Scala.js's <code>fullLinkJS</code>. The output combines the linked JavaScript and CSS under <code>dist/</code>.</p>
<p>For a separate Scala watch process during development, run this in another terminal:</p>
<pre><code class="language-bash">sbt '~fastLinkJS'
</code></pre>
<p><code>fastLinkJS</code> favors a short development cycle; <code>fullLinkJS</code> performs production optimizations. A successful build checks compilation and bundling, while browser interaction still needs its own check.</p>
<h2>Summary</h2>
<p>The flow became easier for me to follow once I separated the roles: sbt and Scala.js produce JavaScript, scalajs-react connects Scala components to React, and Vite serves or bundles the assets. ScalaWind and Tailwind add typed utility classes and the corresponding CSS on top.</p>
<p>I also use this combination in <a href="https://kurashilab.app/">KurashiLab</a>, a personal project about making room for more time and financial flexibility. Revisiting Scala.js has been a fun way to experiment with Scala on the frontend again.</p>
<h2>References</h2>
<ul>
<li><a href="https://www.scala-js.org/doc/tutorial/scalajs-vite.html">Scala.js: Getting Started with Scala.js and Vite</a></li>
<li><a href="https://github.com/scala-js/vite-plugin-scalajs">Scala.js Vite plugin</a></li>
<li><a href="https://github.com/japgolly/scalajs-react">scalajs-react</a></li>
<li><a href="https://github.com/nguyenyou/scalawind">ScalaWind</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Dependency Injection in Python with Protocol and dependency-injector]]></title><description><![CDATA[Use Python Protocol and dependency-injector to connect a service and repository, then test the service with mocks and a handwritten fixture.]]></description><link>https://ara-ta3.hashnode.dev/dependency-injection-in-python-with-protocol-and-dependency-injector</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/dependency-injection-in-python-with-protocol-and-dependency-injector</guid><category><![CDATA[Python]]></category><category><![CDATA[dependency injection]]></category><category><![CDATA[Testing]]></category><category><![CDATA[typing]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Thu, 15 Oct 2026 07:16:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/682a9372fe5ea4247ff9c37e/90ae9241-5f49-4586-aa6e-89726e122cae.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>I like keeping data access behind a repository and passing that repository into a service. When I tried this in Python, I found that <code>typing.Protocol</code> could describe the interface without requiring every implementation to inherit from a shared base class.</p>
<p>In this article, I'll combine a <code>Protocol</code> with <code>dependency-injector</code>, build a small in-memory example, and test the service with both a mock and a handwritten repository fixture.</p>
<p>This is an English adaptation of my <a href="https://zenn.dev/ara_ta3/articles/python-protocol-getting-started">Japanese article on Zenn</a>. The <a href="https://gist.github.com/ara-ta3/e668cd1d90daefe52b95de36c7e29485">original example code</a> is also available.</p>
<p>The examples below use Python 3.10 or later.</p>
<h2>Protocol and dependency injection have different jobs</h2>
<p>A <code>Protocol</code> describes the methods and attributes a type needs to provide. A compatible class does not need to explicitly inherit from it. This is called <strong>structural subtyping</strong>; it reminds me of interfaces in Go.</p>
<p>Type checkers can check whether an implementation matches that contract. Python does not enforce type annotations at runtime, and a <code>Protocol</code> does not automatically create or inject dependencies.</p>
<p>Constructor injection passes the repository into the service. The <code>dependency-injector</code> container assembles those objects using the providers we configure explicitly.</p>
<p>The flow is:</p>
<pre><code class="language-text">Container creates repository
    -&gt; passes repository into UserService
        -&gt; service calls fetch() and put()
</code></pre>
<h2>Define the repository interface</h2>
<p>Create <code>main.py</code> and start with the data classes and protocol:</p>
<pre><code class="language-python">from dataclasses import dataclass
from typing import Protocol


@dataclass
class UserDetail:
    name: str
    email: str


@dataclass
class User:
    id: int
    detail: UserDetail


class UserRepositoryProtocol(Protocol):
    def fetch(self, user_id: int) -&gt; User | None:
        ...

    def put(self, data: User | UserDetail) -&gt; User:
        ...
</code></pre>
<p>In this example, <code>put()</code> creates a user when it receives <code>UserDetail</code>, and saves an existing user when it receives <code>User</code>. This keeps the same small interface as the original experiment.</p>
<h2>Implement the service</h2>
<p>Append this class to <code>main.py</code>:</p>
<pre><code class="language-python">class UserService:
    def __init__(self, user_repository: UserRepositoryProtocol):
        self._user_repository = user_repository

    def create_user(self, detail: UserDetail) -&gt; User:
        return self._user_repository.put(detail)

    def update_user(self, user_id: int, detail: UserDetail) -&gt; User | None:
        user = self._user_repository.fetch(user_id)
        if user is None:
            return None

        user.detail.name = detail.name
        user.detail.email = detail.email
        return self._user_repository.put(user)
</code></pre>
<p>The service only needs <code>fetch()</code> and <code>put()</code>. It does not need to know whether the repository uses memory, a database, or a test fixture.</p>
<h2>Implement an in-memory repository</h2>
<p>Append the following implementation:</p>
<pre><code class="language-python">class UserRepositoryOnMemory:
    def __init__(self):
        self._users: dict[int, User] = {}
        self._next_id = 1

    def fetch(self, user_id: int) -&gt; User | None:
        return self._users.get(user_id)

    def put(self, data: User | UserDetail) -&gt; User:
        if isinstance(data, UserDetail):
            user = User(id=self._next_id, detail=data)
            self._users[user.id] = user
            self._next_id += 1
            return user
        if isinstance(data, User):
            self._users[data.id] = data
            return data
        raise TypeError("Unsupported type for put method")
</code></pre>
<p>There is no <code>UserRepositoryProtocol</code> base class here. The method signatures satisfy the protocol structurally.</p>
<p>This implementation stores mutable objects directly. It is enough for the experiment, but it does not model database transactions or isolation.</p>
<h2>Assemble the application with dependency-injector</h2>
<p>Install the packages in a virtual environment:</p>
<pre><code class="language-bash">python3 -m venv .venv
source .venv/bin/activate
python -m pip install dependency-injector pytest
</code></pre>
<p>Append the container and entry point to <code>main.py</code>:</p>
<pre><code class="language-python">from dependency_injector import containers, providers


class Container(containers.DeclarativeContainer):
    user_repository = providers.Singleton(UserRepositoryOnMemory)
    user_service = providers.Factory(
        UserService,
        user_repository=user_repository,
    )


def main():
    container = Container()
    user_service = container.user_service()

    created_user = user_service.create_user(
        UserDetail(name="Alex", email="alex@example.com")
    )
    print(f"Created user: {created_user}")

    updated_user = user_service.update_user(
        created_user.id,
        UserDetail(name="Alex Smith", email="alex.smith@example.com"),
    )
    print(f"Updated user: {updated_user}")


if __name__ == "__main__":
    main()
</code></pre>
<p><code>Singleton</code> reuses the repository within this container, so the in-memory data survives between service calls. <code>Factory</code> creates a new service when requested, passing in that repository.</p>
<p>The container explicitly supplies <code>user_repository</code>. It does not look up the implementation from the protocol annotation.</p>
<p>Run the application:</p>
<pre><code class="language-bash">python main.py
</code></pre>
<p>Expected output:</p>
<pre><code class="language-text">Created user: User(id=1, detail=UserDetail(name='Alex', email='alex@example.com'))
Updated user: User(id=1, detail=UserDetail(name='Alex Smith', email='alex.smith@example.com'))
</code></pre>
<h2>Test the service with a mock</h2>
<p>Create <code>test_main.py</code>. For these unit tests, constructor injection is enough; we can instantiate the service directly.</p>
<pre><code class="language-python">from unittest.mock import Mock

from main import User, UserDetail, UserRepositoryProtocol, UserService


def test_create_user():
    repository = Mock(spec=UserRepositoryProtocol)
    detail = UserDetail(name="New user", email="new@example.com")
    saved_user = User(id=1, detail=detail)
    repository.put.return_value = saved_user

    service = UserService(repository)
    actual = service.create_user(detail)

    assert actual == saved_user
    repository.put.assert_called_once_with(detail)


def test_update_user():
    repository = Mock(spec=UserRepositoryProtocol)
    existing_user = User(
        id=1,
        detail=UserDetail(name="Old name", email="old@example.com"),
    )
    repository.fetch.return_value = existing_user
    detail = UserDetail(name="New name", email="new@example.com")
    saved_user = User(id=1, detail=detail)
    repository.put.return_value = saved_user

    service = UserService(repository)
    actual = service.update_user(1, detail)

    assert actual == saved_user
    repository.fetch.assert_called_once_with(1)
    repository.put.assert_called_once_with(saved_user)


def test_update_user_not_found():
    repository = Mock(spec=UserRepositoryProtocol)
    repository.fetch.return_value = None

    service = UserService(repository)
    actual = service.update_user(
        99, UserDetail(name="Someone", email="someone@example.com")
    )

    assert actual is None
    repository.fetch.assert_called_once_with(99)
    repository.put.assert_not_called()
</code></pre>
<p><code>Mock(spec=UserRepositoryProtocol)</code> restricts the mock's available attributes to the protocol's interface. It does not check argument types or provide runtime enforcement of the full protocol contract.</p>
<h2>Test with a handwritten repository fixture</h2>
<p>Sometimes I prefer a small fixture that stores users and records calls. Create <code>test_fixture.py</code>:</p>
<pre><code class="language-python">from main import User, UserDetail, UserService


class UserRepositoryFixture:
    def __init__(self):
        self._users: dict[int, User] = {}
        self._next_id = 1
        self.fetch_calls: list[int] = []
        self.put_calls: list[User | UserDetail] = []

    def set_user(self, user: User) -&gt; None:
        self._users[user.id] = user
        self._next_id = max(self._next_id, user.id + 1)

    def fetch(self, user_id: int) -&gt; User | None:
        self.fetch_calls.append(user_id)
        return self._users.get(user_id)

    def put(self, data: User | UserDetail) -&gt; User:
        self.put_calls.append(data)
        if isinstance(data, UserDetail):
            user = User(id=self._next_id, detail=data)
            self._users[user.id] = user
            self._next_id += 1
            return user
        if isinstance(data, User):
            self._users[data.id] = data
            return data
        raise TypeError("Unsupported type for put method")


def test_create_user_with_fixture():
    repository = UserRepositoryFixture()
    detail = UserDetail(name="New user", email="new@example.com")

    actual = UserService(repository).create_user(detail)

    assert actual == User(id=1, detail=detail)
    assert repository.put_calls == [detail]


def test_update_user_with_fixture():
    repository = UserRepositoryFixture()
    repository.set_user(
        User(id=1, detail=UserDetail(name="Old name", email="old@example.com"))
    )
    detail = UserDetail(name="New name", email="new@example.com")

    actual = UserService(repository).update_user(1, detail)

    assert actual == User(id=1, detail=detail)
    assert repository.fetch_calls == [1]
    assert repository.put_calls == [User(id=1, detail=detail)]


def test_update_missing_user_with_fixture():
    repository = UserRepositoryFixture()

    actual = UserService(repository).update_user(
        99, UserDetail(name="Someone", email="someone@example.com")
    )

    assert actual is None
    assert repository.fetch_calls == [99]
    assert repository.put_calls == []
</code></pre>
<p>Run both test files:</p>
<pre><code class="language-bash">python -m pytest -q test_main.py test_fixture.py
</code></pre>
<p>There are six tests: creation, update, and missing-user handling, each checked with a mock and a fixture.</p>
<p>The service accepts the fixture without any special registration. If I need to test application assembly through the container instead, <code>dependency-injector</code> also supports <a href="https://python-dependency-injector.ets-labs.org/providers/overriding.html">overriding providers</a>.</p>
<h2>Summary</h2>
<p><code>Protocol</code> gives the service a structural interface to depend on. Constructor injection lets us pass in an implementation, and <code>dependency-injector</code> centralizes how the application creates and connects those implementations.</p>
<p>I found this combination useful for keeping the service independent of its data source and testing it with small substitutes. For a small program, manually passing the repository is also enough; a container becomes useful when there are more objects to assemble.</p>
<h2>References</h2>
<ul>
<li><a href="https://docs.python.org/3/library/typing.html#typing.Protocol">Python documentation: Protocol</a></li>
<li><a href="https://python-dependency-injector.ets-labs.org/introduction/di_in_python.html">Dependency Injector: Dependency injection and inversion of control in Python</a></li>
<li><a href="https://python-dependency-injector.ets-labs.org/providers/overriding.html">Dependency Injector: Provider overriding</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How to Get the Latest Row per Group in MySQL 8 Using ROW_NUMBER()]]></title><description><![CDATA[Get the latest row per group in MySQL 8 with ROW_NUMBER(). Learn how to handle timestamp ties and compare the query with MAX() plus JOIN.]]></description><link>https://ara-ta3.hashnode.dev/how-to-get-the-latest-row-per-group-in-mysql-8-using-row-number</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/how-to-get-the-latest-row-per-group-in-mysql-8-using-row-number</guid><category><![CDATA[MySQL]]></category><category><![CDATA[SQL]]></category><category><![CDATA[database]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Thu, 15 Oct 2026 07:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/682a9372fe5ea4247ff9c37e/4b73a0d5-5738-4ac5-9722-6a939aed239f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>I sometimes need to get the latest row for each group in MySQL: the most recent login per user, the latest status per order, or the last edit per article.</p>
<p>For MySQL 8.0 and later, <code>ROW_NUMBER()</code> makes this straightforward. Partition the rows by their group, sort each partition from newest to oldest, and keep the row numbered <code>1</code>.</p>
<p>This is an English adaptation of my <a href="https://zenn.dev/ara_ta3/articles/mysql-group-latest-row">Japanese article on Zenn</a>.</p>
<h2>Quick answer: use ROW_NUMBER()</h2>
<p>For an article history table, the query looks like this:</p>
<pre><code class="language-sql">WITH ranked AS (
  SELECT
    h.*,
    ROW_NUMBER() OVER (
      PARTITION BY article_id
      ORDER BY updated_at DESC, id DESC
    ) AS rn
  FROM article_histories AS h
)
SELECT article_id, version, content, updated_at
FROM ranked
WHERE rn = 1
ORDER BY article_id;
</code></pre>
<p><code>updated_at DESC</code> puts the newest edit first. <code>id DESC</code> breaks ties when two edits have the same timestamp, so the query selects exactly one row per article. Here, the rule is to choose the larger ID when timestamps match; that is a tie-breaking rule, not a claim that IDs always represent event time.</p>
<h2>Create a sample history table</h2>
<p>Let's use a table that stores each edit as a separate row:</p>
<pre><code class="language-sql">CREATE TABLE article_histories (
  id BIGINT PRIMARY KEY AUTO_INCREMENT,
  article_id INT NOT NULL,
  version INT NOT NULL,
  content TEXT,
  updated_at DATETIME(6) NOT NULL
);

INSERT INTO article_histories
  (article_id, version, content, updated_at)
VALUES
  (1, 1, 'First draft', '2025-10-01 09:00:00.000000'),
  (1, 2, 'Updated title', '2025-10-05 12:30:00.000000'),
  (2, 1, 'First draft', '2025-10-02 10:00:00.000000'),
  (2, 2, 'Expanded content', '2025-10-06 18:20:10.000000'),
  (3, 1, 'First draft', '2025-10-02 10:00:00.000000');
</code></pre>
<p>Running the query above returns:</p>
<pre><code class="language-text">article_id  version  content           updated_at
1           2        Updated title     2025-10-05 12:30:00.000000
2           2        Expanded content  2025-10-06 18:20:10.000000
3           1        First draft       2025-10-02 10:00:00.000000
</code></pre>
<h2>How the query works</h2>
<p>There are three parts:</p>
<ol>
<li><p><code>PARTITION BY article_id</code> splits the rows into groups, one per article.</p>
</li>
<li><p><code>ORDER BY updated_at DESC, id DESC</code> orders the rows within each group, and <code>ROW_NUMBER()</code> assigns numbers starting at <code>1</code>.</p>
</li>
<li><p>The outer query keeps only <code>rn = 1</code>.</p>
</li>
</ol>
<p>A window function keeps the individual rows available. This matters because we want the content and version from the latest row, rather than just its timestamp.</p>
<p>The common table expression (CTE) gives us a separate query level where we can filter the calculated row number. A derived table works too:</p>
<pre><code class="language-sql">SELECT article_id, version, content, updated_at
FROM (
  SELECT
    h.*,
    ROW_NUMBER() OVER (
      PARTITION BY article_id
      ORDER BY updated_at DESC, id DESC
    ) AS rn
  FROM article_histories AS h
) AS ranked
WHERE rn = 1
ORDER BY article_id;
</code></pre>
<p>I tend to prefer the CTE when a history query starts getting more complicated.</p>
<h2>What happens when timestamps tie?</h2>
<p>Add another edit with the same timestamp as article <code>1</code>'s latest edit:</p>
<pre><code class="language-sql">INSERT INTO article_histories
  (article_id, version, content, updated_at)
VALUES
  (1, 3, 'Corrected title', '2025-10-05 12:30:00.000000');
</code></pre>
<p>The new row gets ID <code>6</code> in this sample. With <code>ORDER BY updated_at DESC, id DESC</code>, the query chooses version <code>3</code> for article <code>1</code>.</p>
<p>If the timestamp is the only ordering column, the query still returns one row per article, but the choice between tied rows is not fully specified. Add a unique tie-breaker that matches the rule you want.</p>
<p>If you want <strong>all rows tied for the latest timestamp</strong>, use <code>RANK()</code> with <code>ORDER BY updated_at DESC</code> instead. In that case, multiple rows can have rank <code>1</code>.</p>
<h2>Alternative: MAX() with JOIN</h2>
<p>For environments without window functions, such as MySQL 5.7, a common approach is to find the maximum timestamp and join it back to the table:</p>
<pre><code class="language-sql">SELECT h.*
FROM article_histories AS h
JOIN (
  SELECT article_id, MAX(updated_at) AS latest_time
  FROM article_histories
  GROUP BY article_id
) AS latest
  ON h.article_id = latest.article_id
  AND h.updated_at = latest.latest_time
ORDER BY h.article_id, h.id;
</code></pre>
<p>This returns <strong>every row matching the latest timestamp</strong>. With the extra sample row above, it returns both versions <code>2</code> and <code>3</code> for article <code>1</code>. It is useful when you want ties, but it is not equivalent to selecting exactly one row per group.</p>
<p>Also, selecting <code>MAX(updated_at)</code> alone does not retrieve the corresponding content. The join is what reconnects the timestamp to its original row.</p>
<h2>Summary</h2>
<table>
<thead>
<tr>
<th>Approach</th>
<th>Result when timestamps tie</th>
<th>MySQL version</th>
</tr>
</thead>
<tbody><tr>
<td><code>ROW_NUMBER()</code> with a unique tie-breaker</td>
<td>Exactly one chosen row per group</td>
<td>8.0+</td>
</tr>
<tr>
<td><code>RANK()</code> ordered by timestamp only</td>
<td>All rows tied for latest</td>
<td>8.0+</td>
</tr>
<tr>
<td><code>MAX()</code> joined back to the table</td>
<td>All rows tied for latest</td>
<td>Works without window functions</td>
</tr>
</tbody></table>
<p>For history tables where I need exactly one latest row per group, <code>ROW_NUMBER()</code> with an explicit tie-breaker is a useful pattern to keep around.</p>
<h2>References</h2>
<ul>
<li><p><a href="https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html">MySQL: Window Function Descriptions</a></p>
</li>
<li><p><a href="https://dev.mysql.com/doc/refman/8.0/en/example-maximum-column-group-row.html">MySQL: The Rows Holding the Group-wise Maximum of a Certain Column</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Parallel Development in a Docker Compose Monorepo with the Codex App and git-wt]]></title><description><![CDATA[Lately, I've been working in a style where I keep multiple tasks running in parallel using the Codex app and git-wt.However, in a docker compose-based…]]></description><link>https://ara-ta3.hashnode.dev/develop-with-codex-and-git-worktrees-on-monorepo</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/develop-with-codex-and-git-worktrees-on-monorepo</guid><category><![CDATA[codex]]></category><category><![CDATA[Git worktree]]></category><category><![CDATA[git-wt]]></category><category><![CDATA[Docker compose]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Sat, 28 Feb 2026 12:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/682a9372fe5ea4247ff9c37e/1c7ad799-9b99-47d5-afd8-2e813b228f18.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<h2>Introduction</h2>
<p>Lately, I've been working in a style where I keep multiple tasks running in parallel using the Codex app and <code>git-wt</code>.<br />However, in a <code>docker compose</code>-based development environment where backend, frontend, and other middleware coexist, I ran into a problem: it was hard to verify build outputs.</p>
<p>Because each task's artifacts stay inside its own worktree, verification usually requires one of these:</p>
<ul>
<li><p>bring artifacts back into the main worktree</p>
</li>
<li><p>start the verification environment in that worktree too (<code>docker compose up</code>)</p>
</li>
</ul>
<p>Running the latter in parallel consumes a lot of machine resources, and doing the former manually every time is tedious.<br />So in this article, I’m leaving a memo on how I operate by creating a review branch in the main worktree, so I can validate build results on the main worktree side.</p>
<h3>TL;DR (3 lines)</h3>
<ul>
<li><p>Split work with multiple worktrees and run parallel development with the Codex app</p>
</li>
<li><p>If it’s hard to create a local environment per worktree, create a review branch in the main worktree</p>
<ul>
<li>In this article, the working directory right after <code>git clone</code> is called the main worktree</li>
</ul>
</li>
<li><p>Use either <code>git-wt</code> or the Codex app’s worktree feature</p>
</li>
</ul>
<h2>About the <code>git-wt</code> command</h2>
<p>As a prerequisite, <code>git worktree</code> is a feature that lets you split working directories by branch within one repository.<br />You can work on multiple branches in parallel without increasing the number of <code>git clone</code>s.</p>
<p>For now, I use <code>git-wt</code> instead of raw <code>git worktree</code> commands.<br /><code>git worktree</code> felt a little hard for me to master directly, while <code>git-wt</code> felt easy enough to run with.</p>
<p><a href="https://github.com/k1LoW/git-wt">https://github.com/k1LoW/git-wt</a></p>
<h3>Install</h3>
<pre><code class="language-zsh">brew install k1LoW/tap/git-wt
</code></pre>
<p>I also add the following as-is from the official documentation:</p>
<pre><code class="language-zsh">eval "$(git wt --init zsh)"
</code></pre>
<h3>Commands I use often</h3>
<pre><code class="language-zsh">git wt                    # list
git wt feature/foo        # move to worktree (or create if missing)
git wt -d feature/foo     # delete (worktree + branch)
git wt -D feature/foo     # force delete
</code></pre>
<p>With <code>git wt &lt;name&gt;</code>, it handles both "move to existing worktree" and "create a new one."<br />I currently use the default <code>git-wt</code> settings.<br />Using <code>-d</code> and <code>-D</code> differently for deletion helps reduce accidental destructive operations.</p>
<h4>Alias example</h4>
<p>I use aliases for many <code>git</code> commands; here I alias <code>gw</code>.<br />I also defined <code>gww</code>, which lets me pick from the <code>git wt</code> list via <code>peco</code> and jump there.</p>
<pre><code class="language-zsh">alias gw='git wt'

function gww () {
	git wt \((git wt | tail -n +2 | peco | awk '{print \)(NF-1)}')
}
</code></pre>
<h2>About the Codex app</h2>
<p>I originally used the <code>codex</code> command in the terminal.<br />With terminal-only usage, control characters occasionally mixed in (I couldn't fully pinpoint why), so I used VSCode as a wrapper.<br />When the Codex app was released, I thought, if I’m launching an app anyway, this is better, so I installed it.<br />In practice, it has been pretty good.</p>
<p>Naturally, it can do most things you can do in a terminal, and it shows Threads (ongoing tasks) on the left, which improves visibility when working in parallel.</p>
<p><a href="https://openai.com/ja-JP/index/introducing-the-codex-app/">https://openai.com/ja-JP/index/introducing-the-codex-app/</a></p>
<h3>About the Codex app’s worktree feature</h3>
<p>Roughly speaking, the Codex app’s worktree feature separates workspaces per task.<br />Even in the same repository, tasks interfere less, so parallel work feels easier.</p>
<p>Looking at <code>.git</code> inside a worktree created by the app, I saw this format:</p>
<pre><code class="language-txt">gitdir: /path/to/repo/.git/worktrees/xxxxx
</code></pre>
<p>So my understanding is that this uses <code>git worktree</code> under the hood rather than a fully separate implementation.</p>
<h3>Difference between <code>git-wt</code> and the Codex app worktree feature</h3>
<p>To be honest, at first I wasn’t using the Codex app worktree feature much because I didn’t fully understand it.<br />But once I looked closely, it relies on <code>git worktree</code>, so worktrees created there also appear in <code>git wt</code> lists.</p>
<p>That said, as far as I can tell right now, I haven’t found a flow in the Codex app that creates a branch first when starting worktree-based tasks.<br />So when I want branch-first workflows, creating them beforehand with <code>git-wt</code> feels easier.</p>
<p>Later on, I noticed that the Codex app actually does have a branch creation entry point near the top of the UI.<br />So these days I think of the split more like this: use the Codex app for branch creation and Thread management, and keep <code>git-wt</code> around for moving across worktrees or terminal-first operations.<br />Especially, <code>git wt &lt;name&gt;</code> still earns its place because it jumps to an existing worktree and creates one if it does not exist yet.</p>
<p>On the other hand, worktrees created with <code>git-wt</code> need to be added manually to Codex app Threads, which is a bit inconvenient.<br />For now I split usage like this: "use <code>git-wt</code> when I want to create a branch first," and "use the Codex app when I prioritize Thread management."</p>
<h3>Convenient function for moving across worktrees</h3>
<p>I used to move by selecting only from <code>ghq list -p</code> with <code>peco</code>.<br />But worktrees created by the Codex app are placed under <code>~/.codex/worktrees</code>, so I also include them via <code>find</code>.</p>
<p>This makes it convenient to move among "main worktree", "under ghq", and "under the Codex app" with a single function.</p>
<pre><code class="language-zsh">function gg () {
    local selected_dir=$(
        {
            printf "%s\n" "$HOME/dotfiles"
            ghq list -p
            find "$HOME/.codex/worktrees" -mindepth 2 -maxdepth 2 -type d
        } | peco --query "$LBUFFER"
    )
    if [ -n "$selected_dir" ]; then
        cd ${selected_dir}
    fi
}
</code></pre>
<h2>Create a branch for review</h2>
<p>As noted in the introduction, when backend / frontend / others are run with <code>docker compose</code>, spinning up full environments per worktree can be too resource-heavy.<br />So I wanted a setup where verification can happen in one place (the main worktree).</p>
<p>With <code>git worktree</code>, even if your work branch hasn’t been pushed to remote, it already exists in local Git.<br />That means you can create a review branch from it in the main worktree.</p>
<p>However, branch names currently in use by <code>git worktree</code> can’t be reused directly, so I create one with a <code>review/</code> prefix instead.<br />Typing this every time is tedious, so I made a helper function.</p>
<pre><code class="language-zsh">function gwreview () {
	local b=$1
	git switch -c review/\(b \)b
}
</code></pre>
<p>For example, if I want to review <code>feature/add-login</code>, I run <code>gwreview feature/add-login</code> to create and switch to <code>review/feature/add-login</code>.</p>
<h2>Conclusion</h2>
<p>I introduced one example workflow for parallel development using the Codex app and <code>git-wt</code>.<br />In a <code>docker compose</code>-based monorepo, creating the same environment in every worktree is often unrealistic, so I centralize verification in the main worktree.</p>
<p>This is a later addition, but the Codex app now also has a branch creation entry point, so starting worktree-based tasks directly from the app has become much easier.<br />At the same time, <code>git-wt</code> is still worth keeping around because it makes jumping between worktrees from the terminal much lighter.</p>
<p>I hope this helps anyone facing similar issues in a similar setup.</p>
]]></content:encoded></item><item><title><![CDATA[Running Supabase Locally and Displaying a Task List with Vite + React]]></title><description><![CDATA[I walked through everything from spinning up Supabase locally to implementing the application UI. All source code is available at: Below is the toolchain…]]></description><link>https://ara-ta3.hashnode.dev/running-supabase-locally-and-displaying-a-task-list-with-vite-react</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/running-supabase-locally-and-displaying-a-task-list-with-vite-react</guid><category><![CDATA[supabase]]></category><category><![CDATA[vite]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[development]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Sun, 29 Jun 2025 02:00:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1751132773603/a90bdcff-fcfb-4f6c-9ed8-8b5798293b31.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<h2 id="heading-this-is-a-brief-memorandum-of-building-a-simple-todo-application-with-typescript-vite-react-powered-by-supabase">This is a brief memorandum of building a simple <strong>TODO</strong> application with <strong>TypeScript + Vite + React</strong> powered by <strong>Supabase</strong>.</h2>
<p>I walked through everything from spinning up Supabase locally to implementing the application UI.</p>
<p>All source code is available at:</p>
<p><a target="_blank" href="https://github.com/ara-ta3/supabase-local-getting-started">https://github.com/ara-ta3/supabase-local-getting-started</a></p>
<p>Below is the toolchain (excerpt from <code>package.json</code>):</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"supabase-local-getting-started"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"packageManager"</span>: <span class="hljs-string">"pnpm@10.12.1"</span>,
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"@supabase/supabase-js"</span>: <span class="hljs-string">"^2.50.2"</span>,
    <span class="hljs-attr">"@types/react"</span>: <span class="hljs-string">"^19.1.8"</span>,
    <span class="hljs-attr">"@types/react-dom"</span>: <span class="hljs-string">"^19.1.6"</span>,
    <span class="hljs-attr">"@vitejs/plugin-react"</span>: <span class="hljs-string">"^4.6.0"</span>,
    <span class="hljs-attr">"react"</span>: <span class="hljs-string">"^19.1.0"</span>,
    <span class="hljs-attr">"react-dom"</span>: <span class="hljs-string">"^19.1.0"</span>,
    <span class="hljs-attr">"supabase"</span>: <span class="hljs-string">"^2.26.9"</span>,
    <span class="hljs-attr">"typescript"</span>: <span class="hljs-string">"^5.8.3"</span>,
    <span class="hljs-attr">"vite"</span>: <span class="hljs-string">"^7.0.0"</span>
  }
}
</code></pre>
<h1 id="heading-setting-up-supabase-locally">Setting Up Supabase Locally</h1>
<h2 id="heading-installing-and-initialising-supabase-cli">Installing and Initialising Supabase CLI</h2>
<p>First, install Supabase CLI and initialise your project. Initialisation creates a <code>supabase/</code> directory with the necessary config files:</p>
<pre><code class="lang-bash">pnpm add supabase
pnpm approve-builds
</code></pre>
<blockquote>
<p><strong>Note</strong> Because <strong>pnpm</strong> does <em>not</em> run <code>postinstall</code> scripts automatically, you must execute <code>pnpm approve-builds</code> so that Supabase’s post-install script is authorised and executed.</p>
</blockquote>
<p>Reference: <a target="_blank" href="https://zenn.dev/ara_ta3/scraps/aee0c57bec5e0b">https://zenn.dev/ara_ta3/scraps/aee0c57bec5e0b</a></p>
<h2 id="heading-starting-the-local-stack">Starting the Local Stack</h2>
<p>Launch the local stack with Docker. This spins up PostgreSQL, Supabase Studio, and the other required services.</p>
<pre><code class="lang-bash">pnpm <span class="hljs-built_in">exec</span> supabase start
</code></pre>
<blockquote>
<p><strong>Note – Colima users</strong> If you see <code>container is not ready: unhealthy</code>, it is often due to <strong>vector</strong> and <strong>logflare</strong> health-checks failing inside Colima. In that case, exclude them with <code>-x</code>:</p>
<pre><code class="lang-bash">pnpm <span class="hljs-built_in">exec</span> supabase start -x vector -x logflare
</code></pre>
<p>Reference: <a target="_blank" href="https://zenn.dev/ara_ta3/scraps/7a3e9c5dfacf81">https://zenn.dev/ara_ta3/scraps/7a3e9c5dfacf81</a></p>
</blockquote>
<p>Upon success, you will see output similar to:</p>
<pre><code class="lang-plaintext">Started supabase local development setup.

         API URL: http://127.0.0.1:54321
     GraphQL URL: http://127.0.0.1:54321/graphql/v1
  S3 Storage URL: http://127.0.0.1:54321/storage/v1/s3
          DB URL: postgresql://postgres:postgres@127.0.0.1:54322/postgres
      Studio URL: http://127.0.0.1:54323
    Inbucket URL: http://127.0.0.1:54324
      JWT secret: your-jwt-secret
        anon key: your-anon-key
service_role key: your-service-role-key
   S3 Access Key: your-s3-access-key
   S3 Secret Key: your-s3-secret-key
       S3 Region: local
</code></pre>
<p>Open <strong>Studio URL</strong> in your browser to manage the database visually.</p>
<h2 id="heading-creating-a-migration">Creating a Migration</h2>
<p>Generate a migration file for the <code>tasks</code> table:</p>
<pre><code class="lang-bash">pnpm <span class="hljs-built_in">exec</span> supabase migration new init
<span class="hljs-comment"># =&gt; supabase/migrations/20250628000000_init.sql</span>
</code></pre>
<p>Edit the generated SQL as follows:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">create</span> <span class="hljs-keyword">table</span> public.tasks (
  <span class="hljs-keyword">id</span>           bigserial primary <span class="hljs-keyword">key</span>,
  title        <span class="hljs-built_in">text</span>        <span class="hljs-keyword">not</span> <span class="hljs-literal">null</span>,
  done         <span class="hljs-built_in">boolean</span>     <span class="hljs-keyword">default</span> <span class="hljs-literal">false</span>,
  inserted_at  timestamptz <span class="hljs-keyword">default</span> <span class="hljs-keyword">now</span>()
);

<span class="hljs-keyword">alter</span> <span class="hljs-keyword">table</span> public.tasks <span class="hljs-keyword">enable</span> <span class="hljs-keyword">row</span> <span class="hljs-keyword">level</span> <span class="hljs-keyword">security</span>;

<span class="hljs-keyword">create</span> <span class="hljs-keyword">policy</span> <span class="hljs-string">"anyone can read"</span> <span class="hljs-keyword">on</span> public.tasks
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">select</span> <span class="hljs-keyword">using</span> (<span class="hljs-literal">true</span>);
</code></pre>
<h3 id="heading-applying-migrations">Applying Migrations</h3>
<p>For local development you have several options:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Behaviour</td></tr>
</thead>
<tbody>
<tr>
<td><code>supabase db reset --local</code></td><td><strong>Resets</strong> the local DB, then runs <em>all</em> migrations and seeds.</td></tr>
<tr>
<td><code>supabase db push --local</code></td><td>Pushes the current schema to the <strong>local</strong> DB (normally targets remote).</td></tr>
<tr>
<td><code>supabase migration up</code></td><td>Applies any migrations that have not yet been run locally.</td></tr>
</tbody>
</table>
</div><pre><code class="lang-bash">pnpm <span class="hljs-built_in">exec</span> supabase db reset --<span class="hljs-built_in">local</span>
pnpm <span class="hljs-built_in">exec</span> supabase db push --<span class="hljs-built_in">local</span>
pnpm <span class="hljs-built_in">exec</span> supabase migration up
</code></pre>
<h2 id="heading-adding-seed-data">Adding Seed Data</h2>
<p>Create <code>supabase/seed.sql</code>:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">insert</span> <span class="hljs-keyword">into</span> public.tasks (title, done)
<span class="hljs-keyword">values</span> (<span class="hljs-string">'Buy groceries'</span>,            <span class="hljs-literal">false</span>),
       (<span class="hljs-string">'Write article'</span>,            <span class="hljs-literal">true</span>),
       (<span class="hljs-string">'Implement tests'</span>,          <span class="hljs-literal">false</span>);
</code></pre>
<p>Because the file is named <code>supabase/seed.sql</code>, it is executed automatically during <code>db reset</code>:</p>
<pre><code class="lang-bash">pnpm <span class="hljs-built_in">exec</span> supabase db reset --<span class="hljs-built_in">local</span>
</code></pre>
<h1 id="heading-creating-the-typescript-vite-react-app">Creating the TypeScript + Vite + React App</h1>
<p>Our front-end only needs the packages already shown in <code>package.json</code>.</p>
<h2 id="heading-configuring-the-supabase-client">Configuring the Supabase Client</h2>
<p><code>src/lib/supabase.ts</code>:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { createClient } <span class="hljs-keyword">from</span> <span class="hljs-string">"@supabase/supabase-js"</span>;

<span class="hljs-keyword">const</span> supabaseUrl     = <span class="hljs-keyword">import</span>.meta.env.VITE_SUPABASE_URL;
<span class="hljs-keyword">const</span> supabaseAnonKey = <span class="hljs-keyword">import</span>.meta.env.VITE_SUPABASE_ANON_KEY;

<span class="hljs-keyword">if</span> (!supabaseUrl || !supabaseAnonKey) {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Supabase environment variables are not set."</span>);
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> supabase = createClient(supabaseUrl, supabaseAnonKey);
</code></pre>
<h2 id="heading-generating-type-definitions">Generating Type Definitions</h2>
<pre><code class="lang-bash">pnpm <span class="hljs-built_in">exec</span> supabase gen types typescript --<span class="hljs-built_in">local</span> src/types/database.types.ts
</code></pre>
<h2 id="heading-implementing-the-task-list">Implementing the Task List</h2>
<p><code>src/App.tsx</code>:</p>
<pre><code class="lang-tsx">import { useEffect, useState } from "react";
import { supabase } from "./lib/supabase";
import type { Database } from "./types/database.types";

type Task = Database["public"]["Tables"]["tasks"]["Row"];

export default function App() {
  const [tasks,   setTasks]   = useState&lt;Task[]&gt;([]);
  const [loading, setLoading] = useState(true);
  const [error,   setError]   = useState&lt;string | null&gt;(null);

  useEffect(() =&gt; {
    fetchTasks();
  }, []);

  async function fetchTasks() {
    try {
      setLoading(true);
      const { data, error } = await supabase.from("tasks").select("*");
      if (error) setError(error.message);
      else       setTasks(data ?? []);
    } catch {
      setError("An unexpected error occurred.");
    } finally {
      setLoading(false);
    }
  }

  if (loading) return &lt;div&gt;Loading…&lt;/div&gt;;
  if (error)   return &lt;div&gt;Error: {error}&lt;/div&gt;;

  return (
    &lt;div&gt;
      &lt;h1&gt;Tasks&lt;/h1&gt;
      {tasks.length === 0 ? (
        &lt;p&gt;No tasks found.&lt;/p&gt;
      ) : (
        &lt;ul&gt;
          {tasks.map((task) =&gt; (
            &lt;li key={task.id}&gt;
              {task.title} – {task.done ? "Done" : "Pending"}
            &lt;/li&gt;
          ))}
        &lt;/ul&gt;
      )}
    &lt;/div&gt;
  );
}
</code></pre>
<p><code>src/main.tsx</code>:</p>
<pre><code class="lang-tsx">import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

createRoot(document.getElementById("root")!).render(
  &lt;StrictMode&gt;
    &lt;App /&gt;
  &lt;/StrictMode&gt;
);
</code></pre>
<p><code>index.html</code>:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Supabase React App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/src/main.tsx"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h1 id="heading-running-the-application">Running the Application</h1>
<pre><code class="lang-bash">pnpm <span class="hljs-built_in">exec</span> vite
</code></pre>
<p>Open <a target="_blank" href="http://localhost:5173">http://localhost:5173</a> and you should see the list of tasks fetched from Supabase.</p>
<h1 id="heading-summary">Summary</h1>
<ul>
<li><p>Supabase CLI lets you stand up a complete local environment with a single command.</p>
</li>
<li><p>Migrations and seed data keep your development database predictable and disposable.</p>
</li>
</ul>
<p>Supabase proved very convenient for rapid prototyping. Unlike Firebase, it offers a full <strong>PostgreSQL</strong> backend, which I consider a significant advantage. I look forward to using it in future projects.</p>
]]></content:encoded></item><item><title><![CDATA[How to Use the entr Command to Automatically Run Scripts on File Change]]></title><description><![CDATA[During development, it's common to want to monitor file changes and automatically run a specific command when a change is detected.In this article, I’ll…]]></description><link>https://ara-ta3.hashnode.dev/how-to-use-the-entr-command-to-automatically-run-scripts-on-file-change</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/how-to-use-the-entr-command-to-automatically-run-scripts-on-file-change</guid><category><![CDATA[linux watch command]]></category><category><![CDATA[Bash]]></category><category><![CDATA[unix]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Sun, 22 Jun 2025 13:00:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1750559288896/40a58687-a402-49e6-b942-b559ff7a81f8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<h1 id="heading-introduction">Introduction</h1>
<p>During development, it's common to want to monitor file changes and automatically run a specific command when a change is detected.<br />In this article, I’ll introduce a useful tool for that purpose: the <code>entr</code> command.</p>
<h1 id="heading-what-is-the-entr-command">What is the <code>entr</code> Command?</h1>
<p><code>entr</code> is a UNIX utility that monitors file changes and executes a specified command when a change is detected.<br />It reads a list of files from standard input and executes the given command if any of those files are modified.</p>
<p><strong>Official Site</strong><br /><a target="_blank" href="https://eradman.com/entrproject/">https://eradman.com/entrproject/</a></p>
<p><strong>GitHub</strong><br /><a target="_blank" href="https://github.com/eradman/entr">https://github.com/eradman/entr</a></p>
<h2 id="heading-installation">Installation</h2>
<p>On macOS, you can use Homebrew, and on Debian-based systems, you can install it with apt.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># macOS (Homebrew)</span>
brew install entr

<span class="hljs-comment"># Ubuntu/Debian</span>
apt install entr
</code></pre>
<h2 id="heading-basic-usage">Basic Usage</h2>
<p><code>entr</code> reads a list of files from standard input and monitors them for changes.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Basic usage</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"filename"</span> | entr <span class="hljs-built_in">command</span>

<span class="hljs-comment"># Example: monitor changes to hoge.txt and run echo</span>
<span class="hljs-comment">## Terminal A</span>
$ ls
hoge.txt
$ <span class="hljs-built_in">echo</span> abc &gt; hoge.txt

<span class="hljs-comment">## Terminal B</span>
$ <span class="hljs-built_in">echo</span> hoge.txt | entr <span class="hljs-built_in">echo</span> fuga
fuga
<span class="hljs-comment"># After running 'echo abc &gt; hoge.txt' in Terminal A,</span>
<span class="hljs-comment"># 'echo fuga' is executed and printed again.</span>
fuga
</code></pre>
<h1 id="heading-practical-use-cases">Practical Use Cases</h1>
<h2 id="heading-run-tests-when-source-or-test-files-change">Run Tests When Source or Test Files Change</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># Monitor test files and run tests</span>
find . -name <span class="hljs-string">"*.test.js"</span> | entr npm <span class="hljs-built_in">test</span>

<span class="hljs-comment"># Monitor TypeScript files and build</span>
find src -name <span class="hljs-string">"*.ts"</span> | entr npm run build

<span class="hljs-comment"># Monitor config file changes</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"config.yml"</span> | entr -r ./restart-service.sh
</code></pre>
<p>Using <code>find</code> is common here, especially when you want to build code while watching for changes.<br />I found <code>entr</code> when I wanted to combine it with the <code>sbt-native-packager</code>'s <code>sbt stage</code> command.</p>
<h1 id="heading-useful-options">Useful Options</h1>
<h2 id="heading-r-restart-the-process">-r: Restart the process</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># Start the server and restart it on file change</span>
find . -name <span class="hljs-string">"*.js"</span> | entr -r node server.js
</code></pre>
<h2 id="heading-c-clear-the-terminal-before-execution">-c: Clear the terminal before execution</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># Clear terminal before running tests</span>
find . -name <span class="hljs-string">"*.go"</span> | entr -c go <span class="hljs-built_in">test</span> ./...
</code></pre>
<h2 id="heading-d-watch-for-directory-changes-as-well">-d: Watch for directory changes as well</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># Monitor directory changes</span>
find . -<span class="hljs-built_in">type</span> d | entr -d <span class="hljs-built_in">echo</span> <span class="hljs-string">"Directory changed"</span>
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>The <code>entr</code> command is a simple yet powerful tool that automatically runs commands when files change.<br />It's extremely helpful for automating tasks like test execution, builds, or server restarts during development.<br />With its minimalistic design and ease of use, it’s an excellent choice when no other tool fits your watch-and-run use case.</p>
<p>This article is a translated version of my original Japanese post.</p>
<p><a target="_blank" href="https://zenn.dev/ara_ta3/articles/entr-watch-files-and-run-commands">https://zenn.dev/ara_ta3/articles/entr-watch-files-and-run-commands</a></p>
]]></content:encoded></item><item><title><![CDATA[How to Enable npm and Node Commands in Claude Code Action Using allowed_tools]]></title><description><![CDATA[Claude Code Action is a feature that assists with code generation and editing via an AI assistant. By default, command execution is restricted for security…]]></description><link>https://ara-ta3.hashnode.dev/claude-code-actions-allowed-tools</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/claude-code-actions-allowed-tools</guid><category><![CDATA[claude.ai]]></category><category><![CDATA[vibe coding]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Thu, 05 Jun 2025 14:00:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1749056654648/6c4a5f0f-87ba-4366-9d51-cd499403aa53.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<h2 id="heading-introduction">Introduction</h2>
<p>Claude Code Action is a feature that assists with code generation and editing via an AI assistant. By default, command execution is restricted for security reasons.<br />This article serves as a memo on how to configure <code>allowed_tools</code> to enable commands like npm to be executed.</p>
<p><a target="_blank" href="https://github.com/anthropics/claude-code-action">https://github.com/anthropics/claude-code-action</a></p>
<h2 id="heading-environment">Environment</h2>
<h3 id="heading-sample-code">Sample Code</h3>
<p>Here's a sample setup.<br />A simple test script using <code>uvu</code> is provided, and the command to run it is defined in the <code>scripts</code> section of <code>package.json</code>.</p>
<p><a target="_blank" href="https://github.com/ara-ta3/claude-code-action-getting-started">https://github.com/ara-ta3/claude-code-action-getting-started</a></p>
<pre><code class="lang-bash">tree
.
├── node_modules
├── package-lock.json
├── package.json
└── sample.test.js

2 directories, 3 files

cat package.json
{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"claude-code-action-getting-started"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span>,
  <span class="hljs-string">"repository"</span>: {
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"git"</span>,
    <span class="hljs-string">"url"</span>: <span class="hljs-string">"git+ssh://git@github.com/ara-ta3/claude-code-action-getting-started.git"</span>
  },
  <span class="hljs-string">"license"</span>: <span class="hljs-string">"ISC"</span>,
  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"test"</span>: <span class="hljs-string">"node sample.test.js"</span>
  },
  <span class="hljs-string">"devDependencies"</span>: {
    <span class="hljs-string">"uvu"</span>: <span class="hljs-string">"^0.5.6"</span>
  }
}

cat sample.test.js
import { <span class="hljs-built_in">test</span> } from <span class="hljs-string">'uvu'</span>;
import * as assert from <span class="hljs-string">'uvu/assert'</span>;

<span class="hljs-built_in">test</span>(<span class="hljs-string">"What's 1000 minus 7?"</span>, () =&gt; {
  assert.is(1000 - 7, 993);
});

test.run();
</code></pre>
<h3 id="heading-verification-issue">Verification Issue</h3>
<p>A test issue was created to try this out with Claude using the following prompt:</p>
<pre><code class="lang-plaintext">@claude I want to test whether commands can be run in this repository.

Please try running the following commands and display the results in a table:

- npm run test
- node sample.test.js
</code></pre>
<p><a target="_blank" href="https://github.com/ara-ta3/claude-code-action-getting-started/issues/2">https://github.com/ara-ta3/claude-code-action-getting-started/issues/2</a></p>
<h2 id="heading-testing-allowedtools">Testing allowed_tools</h2>
<h3 id="heading-summary-first">Summary First</h3>
<ul>
<li><p>Use <code>Bash</code> to allow all bash commands</p>
</li>
<li><p>Use <code>Bash(npm:*),Bash(node:*)</code> to allow specific command categories</p>
</li>
<li><p>Use <code>Bash(npm install),Bash(npm run test)</code> to allow specific subcommands</p>
</li>
</ul>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Configuration</td><td>npm commands</td><td>node commands</td><td>Status</td></tr>
</thead>
<tbody>
<tr>
<td>No allowed_tools</td><td>❌</td><td>❌</td><td>Permission Denied</td></tr>
<tr>
<td><code>Bash(npm*)</code></td><td>❌</td><td>❌</td><td>Syntax Error</td></tr>
<tr>
<td><code>Bash(npm:*)</code></td><td>✅</td><td>❌</td><td>npm only</td></tr>
<tr>
<td><code>Bash(npm:*),Bash(node:*)</code></td><td>✅</td><td>✅</td><td>npm + node</td></tr>
<tr>
<td><code>Bash</code></td><td>✅</td><td>✅</td><td>Full access</td></tr>
<tr>
<td><code>Bash(npm:install),Bash(npm:run)</code></td><td>❌</td><td>❌</td><td>Syntax Error</td></tr>
<tr>
<td><code>Bash(npm install),Bash(npm run test)</code></td><td>✅</td><td>✅</td><td>npm install + npm run test</td></tr>
</tbody>
</table>
</div><h3 id="heading-default-state">Default State</h3>
<p>By default, Claude Code Action restricts all command execution for security.<br />To allow commands like npm, you must explicitly specify them using the <code>allowed_tools</code> configuration.</p>
<h3 id="heading-allowing-all-commands">Allowing All Commands</h3>
<p>To allow all commands, simply use <code>Bash</code>.<br />This grants full permission, so it's best suited for private repositories.</p>
<pre><code class="lang-yaml"><span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Run</span> <span class="hljs-string">Claude</span> <span class="hljs-string">Code</span>
  <span class="hljs-attr">id:</span> <span class="hljs-string">claude</span>
  <span class="hljs-attr">uses:</span> <span class="hljs-string">anthropics/claude-code-action@beta</span>
  <span class="hljs-attr">with:</span>
    <span class="hljs-attr">anthropic_api_key:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.ANTHROPIC_API_KEY</span> <span class="hljs-string">}}</span>
    <span class="hljs-attr">allowed_tools:</span> <span class="hljs-string">"Bash"</span>
</code></pre>
<h3 id="heading-allowing-all-subcommands-for-specific-tools">Allowing All Subcommands for Specific Tools</h3>
<p>To allow all subcommands for specific tools, use syntax like <code>Bash(npm:*),Bash(node:*)</code>.</p>
<pre><code class="lang-yaml"><span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Run</span> <span class="hljs-string">Claude</span> <span class="hljs-string">Code</span>
  <span class="hljs-attr">id:</span> <span class="hljs-string">claude</span>
  <span class="hljs-attr">uses:</span> <span class="hljs-string">anthropics/claude-code-action@beta</span>
  <span class="hljs-attr">with:</span>
    <span class="hljs-attr">anthropic_api_key:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.ANTHROPIC_API_KEY</span> <span class="hljs-string">}}</span>
    <span class="hljs-attr">allowed_tools:</span> <span class="hljs-string">"Bash(npm:*),Bash(node:*)"</span>
</code></pre>
<p>This allows <code>npm</code> and <code>node</code> command families.<br />If the command is defined under <code>scripts</code> in <code>package.json</code>, it may still be executable even if only npm is allowed.</p>
<h3 id="heading-allowing-specific-subcommands">Allowing Specific Subcommands</h3>
<p>To allow specific commands only, use <code>Bash(npm install),Bash(npm run test)</code>.</p>
<pre><code class="lang-yaml"><span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Run</span> <span class="hljs-string">Claude</span> <span class="hljs-string">Code</span>
  <span class="hljs-attr">id:</span> <span class="hljs-string">claude</span>
  <span class="hljs-attr">uses:</span> <span class="hljs-string">anthropics/claude-code-action@beta</span>
  <span class="hljs-attr">with:</span>
    <span class="hljs-attr">anthropic_api_key:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.ANTHROPIC_API_KEY</span> <span class="hljs-string">}}</span>
    <span class="hljs-attr">allowed_tools:</span> <span class="hljs-string">"Bash(npm install),Bash(npm run test)"</span>
</code></pre>
<p>Writing out everything this way can be tedious, so a mix of general and specific permissions may work best.</p>
<h2 id="heading-summary-and-thoughts">Summary and Thoughts</h2>
<p>With <code>Bash(npm:*)</code> and similar configurations, Claude can now execute commands like npm, which makes testing and automation easier.<br />By properly configuring <code>allowed_tools</code>, you can enjoy developing safely and efficiently with @claude. (Claude Code Action is fun to play with, but be mindful of usage costs if you're on a usage-based API plan!)</p>
<p>Note: This article is the English translation of the original Japanese version published on Zenn:<br /><a target="_blank" href="https://zenn.dev/ara_ta3/articles/claude-code-actions-allowed-tools">https://zenn.dev/ara_ta3/articles/claude-code-actions-allowed-tools</a></p>
]]></content:encoded></item><item><title><![CDATA[How to Use Enums in Rust CLI Applications with clap (Command & Option Mapping Guide)]]></title><description><![CDATA[Build robust and maintainable command-line interfaces in Rust using clap's enum support for commands and options.]]></description><link>https://ara-ta3.hashnode.dev/how-to-use-enums-in-rust-cli-applications-with-clap-command-and-option-mapping-guide</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/how-to-use-enums-in-rust-cli-applications-with-clap-command-and-option-mapping-guide</guid><category><![CDATA[Rust]]></category><category><![CDATA[cli]]></category><category><![CDATA[how-to]]></category><category><![CDATA[clap]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Mon, 26 May 2025 15:00:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1748090252433/8d997909-1eae-4719-a08e-dc382b932115.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<h1 id="heading-overview">Overview</h1>
<p>While getting more comfortable with Rust, I decided to try writing a simple CLI.<br />I looked for a library that could elegantly handle commands and found <strong>clap</strong>.<br />This post is a quick note on how to map CLI commands and options to enums using <code>clap</code>.</p>
<p>Base <code>Cargo.toml</code> configuration:</p>
<pre><code class="lang-toml"><span class="hljs-section">[package]</span>
<span class="hljs-attr">name</span> = <span class="hljs-string">"cli-with-clap"</span>
<span class="hljs-attr">version</span> = <span class="hljs-string">"0.1.0"</span>
<span class="hljs-attr">edition</span> = <span class="hljs-string">"2021"</span>

<span class="hljs-section">[dependencies]</span>
<span class="hljs-attr">clap</span> = { version = <span class="hljs-string">"4.5.23"</span>, features = [<span class="hljs-string">"derive"</span>] }
</code></pre>
<h1 id="heading-getting-cli-commands-as-strings">Getting CLI Commands as Strings</h1>
<p>Here’s a basic example where we receive a CLI command as a string:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> clap::Parser;

<span class="hljs-meta">#[derive(Parser, Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Cli</span></span> {
    command: <span class="hljs-built_in">String</span>,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> cli = Cli::parse();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, cli);
}
</code></pre>
<pre><code class="lang-bash">cargo run hoge
Cli { <span class="hljs-built_in">command</span>: <span class="hljs-string">"hoge"</span> }
</code></pre>
<h2 id="heading-adding-options-like-hoge">Adding Options like --hoge</h2>
<p>Using <code>#[arg()]</code>, you can add options to the command:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> clap::Parser;

<span class="hljs-meta">#[derive(Parser, Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Cli</span></span> {
    command: <span class="hljs-built_in">String</span>,

    <span class="hljs-meta">#[arg(short, long, default_value_t = String::from(<span class="hljs-meta-string">""</span>))]</span>
    mojiretu: <span class="hljs-built_in">String</span>,

    <span class="hljs-meta">#[arg(long)]</span>
    maybe_mojiretu: <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">String</span>&gt;,

    <span class="hljs-meta">#[arg(short, long, default_value_t = 0)]</span>
    suuji: <span class="hljs-built_in">u32</span>,

    <span class="hljs-meta">#[arg(short, long)]</span>
    flag: <span class="hljs-built_in">bool</span>,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> cli = Cli::parse();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, cli);
}
</code></pre>
<h1 id="heading-mapping-cli-commands-to-enums">Mapping CLI Commands to Enums</h1>
<p>To map commands to enums, use <code>Subcommand</code>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> clap::{Parser, Subcommand};

<span class="hljs-meta">#[derive(Parser)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Cli</span></span> {
    <span class="hljs-meta">#[command(subcommand)]</span>
    command: Commands,
}

<span class="hljs-meta">#[derive(Subcommand)]</span>
<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Commands</span></span> {
    Add { task: <span class="hljs-built_in">String</span> },
    Remove { task: <span class="hljs-built_in">String</span> },
    List,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> cli = Cli::parse();

    <span class="hljs-keyword">match</span> cli.command {
        Commands::Add { task } =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Add task: {}"</span>, task),
        Commands::Remove { task } =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Remove task: {}"</span>, task),
        Commands::List =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"List tasks"</span>),
    }
}
</code></pre>
<pre><code class="lang-bash">cargo run list
List tasks

cargo run add hoge
Add task: hoge
</code></pre>
<h2 id="heading-explicit-subcommand-name-mapping-with-commandname">Explicit Subcommand Name Mapping with <code>command(name="")</code></h2>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> clap::{Parser, Subcommand};

<span class="hljs-meta">#[derive(Parser, Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Cli</span></span> {
    <span class="hljs-meta">#[command(subcommand)]</span>
    command: Commands,
}

<span class="hljs-meta">#[derive(Subcommand, Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Commands</span></span> {
    <span class="hljs-meta">#[command(name = <span class="hljs-meta-string">"hogefuga"</span>)]</span>
    FooBar,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> cli = Cli::parse();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, cli);
}
</code></pre>
<pre><code class="lang-bash">cargo run hogefuga
Cli { <span class="hljs-built_in">command</span>: FooBar }
</code></pre>
<h2 id="heading-change-subcommand-case-mapping-with-renameall">Change Subcommand Case Mapping with <code>rename_all</code></h2>
<p>By default, subcommand names use kebab-case. You can change this with <code>rename_all</code>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> clap::{Parser, Subcommand};

<span class="hljs-meta">#[derive(Parser, Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Cli</span></span> {
    <span class="hljs-meta">#[command(subcommand)]</span>
    command: Commands,
}

<span class="hljs-meta">#[derive(Subcommand, Debug)]</span>
<span class="hljs-meta">#[command(rename_all = <span class="hljs-meta-string">"snake_case"</span>)]</span>
<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Commands</span></span> {
    FooBar,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> cli = Cli::parse();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, cli);
}
</code></pre>
<pre><code class="lang-bash">cargo run foo_bar
Cli { <span class="hljs-built_in">command</span>: FooBar }
</code></pre>
<h1 id="heading-getting-cli-options-as-enums">Getting CLI Options as Enums</h1>
<p>To map CLI options to enums, use <code>ValueEnum</code>:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> clap::{Parser, ValueEnum};

<span class="hljs-meta">#[derive(Parser, Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Cli</span></span> {
    <span class="hljs-meta">#[arg(short, long)]</span>
    log_level: Level,
}

<span class="hljs-meta">#[derive(Debug, Clone, ValueEnum)]</span>
<span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Level</span></span> {
    <span class="hljs-built_in">Debug</span>,
    Info,
    Error,
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> cli = Cli::parse();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, cli);
}
</code></pre>
<pre><code class="lang-bash">cargo run -- --log-level info
Cli { log_level: Info }
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<ul>
<li><p>Achieved everything without much hassle</p>
</li>
<li><p><code>clap</code> + <code>derive</code> is powerful</p>
</li>
<li><p>Enum-based commands make Rust's pattern matching extremely ergonomic</p>
</li>
</ul>
<p>This article is an English translation of the original post published on Zenn: <a target="_blank" href="https://zenn.dev/ara_ta3/articles/rust-cli-with-clap-bind-enum">https://zenn.dev/ara_ta3/articles/rust-cli-with-clap-bind-enum</a>.</p>
]]></content:encoded></item><item><title><![CDATA[How to Test Bash Scripts Using Bats]]></title><description><![CDATA[Learn how to write and run automated tests for your shell scripts using the Bats testing framework.]]></description><link>https://ara-ta3.hashnode.dev/how-to-test-bash-scripts-using-bats</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/how-to-test-bash-scripts-using-bats</guid><category><![CDATA[bats]]></category><category><![CDATA[shell script]]></category><category><![CDATA[Testing]]></category><category><![CDATA[test-automation]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Sun, 25 May 2025 15:00:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1748089701718/1788852a-0d4d-4616-a4c0-a03d8c295f05.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-overview">Overview</h1>
<p><a target="_blank" href="https://github.com/bats-core/bats-core">https://github.com/bats-core/bats-core</a></p>
<p>Bats is a testing framework for Bash.<br />I discovered it when I wanted to add tests to a simple script that didn’t need to be written in a full programming language.<br />Here, I introduce some basic examples of Bats test code.</p>
<p>The code examples shown in this article are available here:<br /><a target="_blank" href="https://gist.github.com/ara-ta3/df3bbd45b916bc137fb6196ce2e213d9">https://gist.github.com/ara-ta3/df3bbd45b916bc137fb6196ce2e213d9</a></p>
<p>I installed Bats via Homebrew and used version 1.11.0:<br /><a target="_blank" href="https://formulae.brew.sh/formula/bats-core">https://formulae.brew.sh/formula/bats-core</a></p>
<pre><code class="lang-bash">&gt; bats --version
Bats 1.11.0
</code></pre>
<h1 id="heading-simple-test-code">Simple Test Code</h1>
<p>Bats test code is written in separate files from shell scripts. You run the tests by executing the test file with the <code>bats</code> command.<br />Test cases are defined like this:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/usr/bin/env bats</span>

@<span class="hljs-built_in">test</span> <span class="hljs-string">"echo hoge"</span> {
    result=$(<span class="hljs-built_in">echo</span> hoge)
    [ <span class="hljs-string">"<span class="hljs-variable">$result</span>"</span> = <span class="hljs-string">"hoge"</span> ]
}

@<span class="hljs-built_in">test</span> <span class="hljs-string">"echo hoge expected to fuga"</span> {
    result=$(<span class="hljs-built_in">echo</span> hoge)
    [ <span class="hljs-string">"<span class="hljs-variable">$result</span>"</span> = <span class="hljs-string">"fuga"</span> ]
}
</code></pre>
<p>Running it gives:</p>
<pre><code class="lang-plaintext">&gt; bats test_simple.bats
test_simple.bats
 ✓ echo hoge
 ✗ echo hoge expected to fuga
   (in test file test_simple.bats, line 10)
     `[ "$result" = "fuga" ]' failed

2 tests, 1 failure
</code></pre>
<h2 id="heading-the-run-helper-and-special-global-variables">The <code>run</code> Helper and Special Global Variables</h2>
<p>Bats provides a <code>run</code> helper command that captures the output and status of a command into special global variables:</p>
<ul>
<li><p><code>$status</code>: The exit code</p>
</li>
<li><p><code>$output</code>: Combined stdout and stderr (can be separated with <code>--separate-stderr</code>)</p>
</li>
<li><p><code>$lines</code>: Array of lines split from <code>$output</code></p>
</li>
</ul>
<p><a target="_blank" href="https://github.com/bats-core/bats-core/blob/b640ec3cf2c7c9cfc9e6351479261186f76eeec8/man/bats.7.ronn?plain=1#L94">https://github.com/bats-core/bats-core/blob/b640ec3cf2c7c9cfc9e6351479261186f76eeec8/man/bats.7.ronn?plain=1#L94</a></p>
<p>Example:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/usr/bin/env bats</span>

@<span class="hljs-built_in">test</span> <span class="hljs-string">"exit with 0 with status variable"</span> {
    run <span class="hljs-built_in">test</span> 1 -eq 1 
    [ <span class="hljs-string">"<span class="hljs-variable">$status</span>"</span> -eq 0 ]
}

@<span class="hljs-built_in">test</span> <span class="hljs-string">"1 + 1 = 2 with output variable"</span> {
    run <span class="hljs-built_in">echo</span> $((<span class="hljs-number">1</span>+<span class="hljs-number">1</span>))
    [ <span class="hljs-string">"<span class="hljs-variable">$output</span>"</span> -eq 2 ]
}
</code></pre>
<p>Result:</p>
<pre><code class="lang-bash">&gt; bats test_simple_global_vars.bats
test_simple_global_vars.bats
 ✓ <span class="hljs-built_in">exit</span> with 0 with status variable
 ✓ 1 + 1 = 2 with output variable

2 tests, 0 failures
</code></pre>
<h2 id="heading-options-for-the-run-helper">Options for the <code>run</code> Helper</h2>
<p>The <code>run</code> command supports options for asserting exit codes directly.</p>
<p><a target="_blank" href="https://github.com/bats-core/bats-core/blob/b640ec3cf2c7c9cfc9e6351479261186f76eeec8/docs/source/writing-tests.md?plain=1#L150-L165">https://github.com/bats-core/bats-core/blob/b640ec3cf2c7c9cfc9e6351479261186f76eeec8/docs/source/writing-tests.md?plain=1#L150-L165</a></p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/usr/bin/env bats</span>

<span class="hljs-function"><span class="hljs-title">setup</span></span>() {
    <span class="hljs-comment"># Ensure minimum version to use run options</span>
    bats_require_minimum_version 1.5.0
}

@<span class="hljs-built_in">test</span> <span class="hljs-string">"(expected to fail) exit with non 0 with ! option"</span> {
    run ! -- <span class="hljs-built_in">test</span> 1 -eq 1 
}

@<span class="hljs-built_in">test</span> <span class="hljs-string">"(expected to fail) exit with non 0 with -N option"</span> {
    run -1 -- <span class="hljs-built_in">test</span> 1 -eq 1 
}
</code></pre>
<p>Result:</p>
<pre><code class="lang-bash">&gt; bats test_simple_run_helper.bats
test_simple_run_helper.bats
 ✗ (expected to fail) <span class="hljs-built_in">exit</span> with non 0 with ! option
   `run ! -- <span class="hljs-built_in">test</span> 1 -eq 1 <span class="hljs-string">' failed, expected nonzero exit code!
 ✗ (expected to fail) exit with non 0 with -N option
   `run -1 -- test 1 -eq 1 '</span> failed, expected <span class="hljs-built_in">exit</span> code 1, got 0

2 tests, 2 failures
</code></pre>
<h2 id="heading-tagging-and-filtering-tests">Tagging and Filtering Tests</h2>
<p>You can assign tags to tests with comments, and use <code>--filter-tags</code> to run only tests with specific tags:</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/usr/bin/env bats</span>

<span class="hljs-comment"># bats test_tags=1digits</span>
@<span class="hljs-built_in">test</span> <span class="hljs-string">"1 + 1 = 2"</span> {
    run <span class="hljs-built_in">echo</span> $((<span class="hljs-number">1</span>+<span class="hljs-number">1</span>))
    [ <span class="hljs-string">"<span class="hljs-variable">$output</span>"</span> -eq 2 ]
}

<span class="hljs-comment"># bats test_tags=2digits</span>
@<span class="hljs-built_in">test</span> <span class="hljs-string">"10 + 15 = 25"</span> {
    run <span class="hljs-built_in">echo</span> $((<span class="hljs-number">10</span>+<span class="hljs-number">15</span>))
    [ <span class="hljs-string">"<span class="hljs-variable">$output</span>"</span> -eq 25 ]
}
</code></pre>
<pre><code class="lang-bash">&gt; bats --filter-tags 1digits ./test_tags.bats
 ✓ 1 + 1 = 2

&gt; bats --filter-tags 2digits ./test_tags.bats
 ✓ 10 + 15 = 25
</code></pre>
<h3 id="heading-using-the-batsfocus-tag-to-run-a-single-test">Using the <code>bats:focus</code> Tag to Run a Single Test</h3>
<pre><code class="lang-bash"><span class="hljs-meta">#!/usr/bin/env bats</span>

<span class="hljs-comment"># bats test_tags=bats:focus</span>
@<span class="hljs-built_in">test</span> <span class="hljs-string">"focus echo"</span> {
    run <span class="hljs-built_in">echo</span> hoge
    [ <span class="hljs-string">"<span class="hljs-variable">$output</span>"</span> = <span class="hljs-string">"hoge"</span> ]
}

@<span class="hljs-built_in">test</span> <span class="hljs-string">"not focus echo fuga"</span> {
    run <span class="hljs-built_in">echo</span> fuga
    [ <span class="hljs-string">"<span class="hljs-variable">$output</span>"</span> = <span class="hljs-string">"fuga"</span> ]
}
</code></pre>
<pre><code class="lang-bash">&gt; bats ./test_tags_focus.bats
WARNING: This <span class="hljs-built_in">test</span> run only contains tests tagged `bats:focus`!
ok 1 focus <span class="hljs-built_in">echo</span>
Marking <span class="hljs-built_in">test</span> run as failed due to `bats:focus` tag. (Set `BATS_NO_FAIL_FOCUS_RUN=1` to <span class="hljs-built_in">disable</span>.)
</code></pre>
<h2 id="heading-testing-with-external-functions">Testing with External Functions</h2>
<p>You can split functions into a separate file and test them by sourcing them in the <code>setup</code> function:</p>
<p><a target="_blank" href="http://functions.sh"><strong>functions.sh</strong></a></p>
<pre><code class="lang-bash"><span class="hljs-function"><span class="hljs-title">get_day_of_week</span></span>() {
    <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">${TEST_DAY:-$(gdate +%u)}</span>"</span>
}

<span class="hljs-function"><span class="hljs-title">should_run_main</span></span>() {
    <span class="hljs-built_in">local</span> day_of_week=$(get_day_of_week)
    <span class="hljs-keyword">if</span> [[ <span class="hljs-string">"<span class="hljs-variable">$day_of_week</span>"</span> -eq 6 || <span class="hljs-string">"<span class="hljs-variable">$day_of_week</span>"</span> -eq 7 ]]; <span class="hljs-keyword">then</span>
        <span class="hljs-built_in">return</span> 1
    <span class="hljs-keyword">fi</span>
    <span class="hljs-built_in">return</span> 0
}

<span class="hljs-function"><span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">if</span> ! should_run_main; <span class="hljs-keyword">then</span>
        <span class="hljs-built_in">return</span>
    <span class="hljs-keyword">fi</span>
    <span class="hljs-built_in">echo</span> <span class="hljs-string">"main is running"</span>
}
</code></pre>
<p><strong>test_functions.bats</strong></p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/usr/bin/env bats</span>

<span class="hljs-function"><span class="hljs-title">setup</span></span> () {
    <span class="hljs-built_in">source</span> <span class="hljs-string">"./functions.sh"</span>
}

@<span class="hljs-built_in">test</span> <span class="hljs-string">"on Monday should_run_main returns 0"</span> {
    TEST_DAY=1
    run should_run_main
    [ <span class="hljs-string">"<span class="hljs-variable">$status</span>"</span> -eq 0 ]
}

@<span class="hljs-built_in">test</span> <span class="hljs-string">"on Sunday should_run_main returns 1"</span> {
    TEST_DAY=7
    run should_run_main
    [ <span class="hljs-string">"<span class="hljs-variable">$status</span>"</span> -eq 1 ]
}
</code></pre>
<pre><code class="lang-bash">&gt; bats test_functions.bats
 ✓ on Monday should_run_main returns 0
 ✓ on Sunday should_run_main returns 1

2 tests, 0 failures
</code></pre>
<h2 id="heading-notes-eg-assertoutput">Notes (e.g. assert_output)</h2>
<p>Although not used in this article, helper functions like <code>assert_output</code> are available:<br /><a target="_blank" href="https://github.com/bats-core/bats-assert￼https://bats-core.readthedocs.io/en/stable/tutorial.html#quick-installation">https://github.com/bats-core/bats-assert<br />https://bats-core.readthedocs.io/en/stable/tutorial.html#quick-installation</a></p>
<h1 id="heading-conclusion">Conclusion</h1>
<ul>
<li><p>Bats is useful for testing shell scripts.</p>
</li>
<li><p><s>For larger projects, using a language like Go might be more appropriate.</s></p>
</li>
<li><p>It’s easy to use and ideal for lightweight, quickly written scripts.</p>
</li>
</ul>
<p>Note: This article is an English translation of the original post published on Zenn: <a target="_blank" href="https://zenn.dev/ara_ta3/articles/shell-script-test-with-bats">https://zenn.dev/ara_ta3/articles/shell-script-test-with-bats</a>.</p>
]]></content:encoded></item><item><title><![CDATA[How to Generate JSON with jq and Send Slack Messages via Webhook.]]></title><description><![CDATA[Use jq -n, --arg, and curl to create JSON and automate Slack notifications effortlessly]]></description><link>https://ara-ta3.hashnode.dev/how-to-generate-json-with-jq-and-send-slack-messages-via-webhook</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/how-to-generate-json-with-jq-and-send-slack-messages-via-webhook</guid><category><![CDATA[jq]]></category><category><![CDATA[slack]]></category><category><![CDATA[webhooks]]></category><category><![CDATA[json]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Sat, 24 May 2025 15:00:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1748089150573/7520379c-f79a-4cbb-88e3-58c4b7b19ca3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When parsing JSON to extract information, I’ve often used the <code>jq</code> command. This time, I realized it can also be used to <strong>generate</strong> JSON, so I decided to write this as a quick memo.</p>
<p>While I was casually writing a script that processes a string retrieved via <code>curl</code> and sends a notification to Slack, I found that using <code>jq -n</code> (or <code>--null-input</code>) and <code>--arg</code> was convenient for generating JSON and directly sending it to Slack’s Incoming Webhook.</p>
<p>Here’s the version of <code>jq</code> I used at the time:</p>
<pre><code class="lang-bash">jq --version
jq-1.7.1
</code></pre>
<ul>
<li><p>About the jq command:</p>
<ul>
<li><a target="_blank" href="https://jqlang.github.io/jq/">https://jqlang.github.io/jq/</a></li>
</ul>
</li>
</ul>
<h1 id="heading-generate-json-with-jq-null-input-and-arg">Generate JSON with jq --null-input and --arg</h1>
<p>The <code>-n</code> (or <code>--null-input</code>) option in <code>jq</code> is handy when generating JSON from scratch without requiring any input data.<br />Using the <code>--arg</code> option, you can name variables and insert them into JSON fields like this:</p>
<pre><code class="lang-bash">jq -n --arg name <span class="hljs-string">"Foo"</span> --arg age <span class="hljs-string">"30"</span> <span class="hljs-string">'{name: $name, age: $age}'</span>
{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Foo"</span>,
  <span class="hljs-string">"age"</span>: <span class="hljs-string">"30"</span>
}
</code></pre>
<h2 id="heading-argjson">--argjson</h2>
<p><code>--argjson</code> is similar to <code>--arg</code>, but it allows the value to be treated as JSON:</p>
<pre><code class="lang-bash">jq -n --argjson data <span class="hljs-string">'{"foo": "bar"}'</span> <span class="hljs-string">'{user: $data}'</span>
{
  <span class="hljs-string">"user"</span>: {
    <span class="hljs-string">"foo"</span>: <span class="hljs-string">"bar"</span>
  }
}
</code></pre>
<p>Of course, you can also insert JSON generated by another <code>jq</code> command:</p>
<pre><code class="lang-bash">jq -n --argjson data <span class="hljs-string">"<span class="hljs-subst">$(jq -n --arg name Foo --arg age 30 '{name: $name, age: $age}' )</span>"</span> <span class="hljs-string">'{user: $data}'</span>
{
  <span class="hljs-string">"user"</span>: {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Foo"</span>,
    <span class="hljs-string">"age"</span>: <span class="hljs-string">"30"</span>
  }
}
</code></pre>
<h2 id="heading-args">--args</h2>
<p>The <code>--args</code> option allows you to pass multiple values and access them using <code>$ARGS.positional</code> as an array:</p>
<pre><code class="lang-bash">jq -n --args <span class="hljs-string">'$ARGS.positional'</span> hoge fuga piyo
[
  <span class="hljs-string">"hoge"</span>,
  <span class="hljs-string">"fuga"</span>,
  <span class="hljs-string">"piyo"</span>
]
</code></pre>
<p>It seems that when you use <code>--args</code>, the values are passed under the <code>positional</code> key in <code>$ARGS</code>.<br />Also, values passed via <code>--arg</code> go under the <code>named</code> key:</p>
<pre><code class="lang-bash">jq -n --args <span class="hljs-string">'$ARGS'</span> hoge fuga piyo
{
  <span class="hljs-string">"positional"</span>: [
    <span class="hljs-string">"hoge"</span>,
    <span class="hljs-string">"fuga"</span>,
    <span class="hljs-string">"piyo"</span>
  ],
  <span class="hljs-string">"named"</span>: {}
}

jq -n --args <span class="hljs-string">'$ARGS'</span> hoge fuga piyo --arg hoge fuga
{
  <span class="hljs-string">"positional"</span>: [
    <span class="hljs-string">"hoge"</span>,
    <span class="hljs-string">"fuga"</span>,
    <span class="hljs-string">"piyo"</span>
  ],
  <span class="hljs-string">"named"</span>: {
    <span class="hljs-string">"hoge"</span>: <span class="hljs-string">"fuga"</span>
  }
}
</code></pre>
<h2 id="heading-jsonargs">--jsonargs</h2>
<p>Just like how <code>--argjson</code> relates to <code>--arg</code>, use <code>--jsonargs</code> if you want the values passed to <code>--args</code> to be treated as JSON:</p>
<pre><code class="lang-bash">jq -n --jsonargs <span class="hljs-string">'$ARGS.positional'</span> <span class="hljs-string">'{"name": "foo"}'</span> <span class="hljs-string">'{"name": "bar"}'</span>
[
  {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"foo"</span>
  },
  {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"bar"</span>
  }
]
</code></pre>
<h1 id="heading-send-the-generated-json-to-a-webhook-in-one-liner">Send the Generated JSON to a Webhook in One-liner</h1>
<p>Use <code>curl</code> to send the generated JSON to Slack’s Incoming Webhook like this:</p>
<pre><code class="lang-bash">jq -n --arg text <span class="hljs-string">"Foo"</span> <span class="hljs-string">'{text: $text}'</span> | curl -X POST -H <span class="hljs-string">'Content-type: application/json'</span> --data @- https://hooks.slack.com/services/your/webhook/url
</code></pre>
<h2 id="heading-use-to-pass-stdin-as-data-to-curl">Use @- to Pass stdin as --data to curl</h2>
<p>Using <code>@-</code> as the argument for <code>--data</code> allows you to pass standard input.<br />This is something I learned through this process—it’s also usable in other places.</p>
<p><a target="_blank" href="https://curl.se/docs/manpage.html">https://curl.se/docs/manpage.html</a></p>
<blockquote>
<p>If you start the data with the letter @, the rest should be a filename to read the data from, or - if you want curl to read the data from stdin.</p>
</blockquote>
<h1 id="heading-conclusion">Conclusion</h1>
<p>This was about using <code>jq --null-input</code> and <code>--arg</code> to generate JSON and send it to Slack.<br />I found it really convenient for sending simple notifications and plan to use it more in the future.</p>
<h1 id="heading-references">References</h1>
<ul>
<li><p><a target="_blank" href="https://jqlang.github.io/jq/">https://jqlang.github.io/jq/</a></p>
</li>
<li><p><a target="_blank" href="https://api.slack.com/messaging/webhooks">https://api.slack.com/messaging/webhooks</a></p>
</li>
</ul>
<p>Note: This article is an English translation of the original Japanese post published on Zenn: <a target="_blank" href="https://zenn.dev/ara_ta3/articles/send-incoming-webhook-with-jq">https://zenn.dev/ara_ta3/articles/send-incoming-webhook-with-jq</a></p>
]]></content:encoded></item><item><title><![CDATA[Pre-rendering Dynamic React Routes with Meta Tags Using Vike + Vite]]></title><description><![CDATA[Use SSG to pre-render dynamic React pages with meta info via Vike and Vite]]></description><link>https://ara-ta3.hashnode.dev/typescript-vike-ssg-with-dynamic-routing</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/typescript-vike-ssg-with-dynamic-routing</guid><category><![CDATA[React]]></category><category><![CDATA[ssg]]></category><category><![CDATA[vite]]></category><category><![CDATA[vike]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Fri, 23 May 2025 15:00:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1748012004179/e953cf4b-1622-4d99-9f8b-164871507c22.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<h2 id="heading-introduction">Introduction</h2>
<p>Previously, I wrote an article titled <a target="_blank" href="https://ara-ta3.hashnode.dev/how-to-use-vike-for-ssg-in-a-vite-typescript-and-react-project">How to Use Vike for SSG in a Vite, TypeScript, and React Project</a> where I explored SSG with Vite and Vike.<br />In this article, I share my experience embedding meta information like title and description into dynamic pages (e.g., <code>/hoge/:id</code>) and performing SSG.</p>
<p>The versions of the tools used are as follows:</p>
<pre><code class="lang-plaintext">"@vitejs/plugin-react": "^4.4.1",
"typescript": "^5.8.3",
"vike": "^0.4.229",
"vike-react": "^0.6.1",
"vite": "^6.3.5"
</code></pre>
<p>GitHub Repository:<br /><a target="_blank" href="https://github.com/ara-ta3/vike-ssg-dynamic-pages-getting-started">https://github.com/ara-ta3/vike-ssg-dynamic-pages-getting-started</a></p>
<h2 id="heading-preparation">Preparation</h2>
<p>We'll be using the <code>vike-react</code> plugin.<br />In my previous article, I tried an approach without <code>vike-react</code>, but it seems rare not to use it, so this article assumes its use.</p>
<p>Vike settings are now defined in <code>src/pages/+config.ts</code>.<br />While they were previously in <code>vike.config.js</code>, doing so now triggers a warning:</p>
<pre><code class="lang-plaintext">23:00:00 [vike][Warning] Define Vike settings in +config.js instead of vite.config.js https://vike.dev/migration/settings
</code></pre>
<p>Here’s how the configuration file looks:<br /><code>src/pages/+config.ts</code></p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> vikeReact <span class="hljs-keyword">from</span> <span class="hljs-string">"vike-react/config"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  <span class="hljs-keyword">extends</span>: [vikeReact],
  prerender: <span class="hljs-literal">true</span>,
};
</code></pre>
<h2 id="heading-overview">Overview</h2>
<p>Here’s what we’ll be doing:</p>
<ul>
<li><p>Define dynamic route path in <code>+route.ts</code></p>
</li>
<li><p>Create page content in <code>+Page.tsx</code></p>
</li>
<li><p>Fetch title in <code>+onBeforeRender.ts</code> and pass to <code>pageContext</code></p>
</li>
<li><p>Output meta info in <code>+Head.tsx</code></p>
</li>
<li><p>List static paths in <code>+onBeforePrerenderStart.ts</code></p>
</li>
</ul>
<p>Final directory structure under <code>src/pages/hoge</code>:</p>
<pre><code class="lang-plaintext">src
└── pages
    ├── +config.ts
    ├── +Head.tsx
    ├── +Page.tsx
    └── hoge
        ├── +Head.tsx
        ├── +onBeforePrerenderStart.ts
        ├── +onBeforeRender.ts
        ├── +Page.tsx
        └── +route.ts
</code></pre>
<h2 id="heading-defining-the-dynamic-route-routets">Defining the Dynamic Route (<code>+route.ts</code>)</h2>
<p>Enable handling of dynamic route <code>/hoge/@id</code>:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-string">"/hoge/@id"</span>;
</code></pre>
<p><a target="_blank" href="https://vike.dev/route">https://vike.dev/route</a></p>
<h2 id="heading-creating-page-content-pagetsx">Creating Page Content (<code>+Page.tsx</code>)</h2>
<p>Props aren't passed directly, so use <code>usePageContext()</code>.<br />The <code>PageContext</code> generic is defined as <code>PageContext&lt;Data = unknown&gt;</code>, so we use <code>as</code> to specify the data shape:</p>
<pre><code class="lang-tsx">import { usePageContext } from "vike-react/usePageContext";
import { PageContext } from "vike/types";

export { Page };

function Page() {
  const c = usePageContext() as PageContext&lt;{
    id: number;
    title: string;
    description: string;
  }&gt;;
  const title = c.data.title;
  const description = c.data.description;

  return (
    &lt;div&gt;
      &lt;p&gt;hello {c.data.id}&lt;/p&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p><a target="_blank" href="https://vike.dev/Page">https://vike.dev/Page</a></p>
<h2 id="heading-fetching-data-and-passing-meta-info-to-pagecontext-onbeforerenderts">Fetching Data and Passing Meta Info to <code>PageContext</code> (<code>+onBeforeRender.ts</code>)</h2>
<p>Retrieve data and return it as <code>pageContext</code>:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { PageContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"vike/types"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onBeforeRender</span>(<span class="hljs-params">pageContext: PageContext</span>) </span>{
  <span class="hljs-keyword">const</span> id = <span class="hljs-built_in">parseInt</span>(pageContext.routeParams.id);
  <span class="hljs-keyword">let</span> title = <span class="hljs-string">"Hoge null"</span>;
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">isNaN</span>(id)) {
    <span class="hljs-keyword">return</span> {
      pageContext: {
        data: { id, title, description: <span class="hljs-string">"Hoge null"</span> },
      },
    };
  }
  title = <span class="hljs-string">`Hoge <span class="hljs-subst">${id}</span>`</span>;
  <span class="hljs-keyword">return</span> {
    pageContext: {
      data: { id, title: <span class="hljs-string">`Hoge <span class="hljs-subst">${id}</span>`</span>, description: <span class="hljs-string">`Hoge <span class="hljs-subst">${id}</span>`</span> },
    },
  };
}
</code></pre>
<p><a target="_blank" href="https://vike.dev/onBeforeRender">https://vike.dev/onBeforeRender</a></p>
<h2 id="heading-outputting-meta-info-headtsx">Outputting Meta Info (<code>+Head.tsx</code>)</h2>
<p>Responsible for outputting meta info:</p>
<pre><code class="lang-tsx">import React from "react";
import { usePageContext } from "vike-react/usePageContext";
import { PageContext } from "vike/types";

const Head: React.FC = () =&gt; {
  const c = usePageContext() as PageContext&lt;{
    id: number;
    title: string;
    description: string;
  }&gt;;

  const title = c.data.title;
  const description = c.data.description;

  return (
    &lt;&gt;
      &lt;title&gt;{title}&lt;/title&gt;
      &lt;meta name="description" content={description} /&gt;
      &lt;meta property="og:title" content={title} /&gt;
      &lt;meta property="og:description" content={description} /&gt;
      &lt;meta property="og:type" content="website" /&gt;
      &lt;meta charSet="UTF-8" /&gt;
    &lt;/&gt;
  );
};

export default Head;
</code></pre>
<p><a target="_blank" href="https://vike.dev/head-tags#head-setting">https://vike.dev/head-tags#head-setting</a></p>
<h2 id="heading-listing-static-paths-onbeforeprerenderstartts">Listing Static Paths (<code>+onBeforePrerenderStart.ts</code>)</h2>
<p>Enumerate the paths for prerendering:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> { onBeforePrerenderStart };

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onBeforePrerenderStart</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> ids = [<span class="hljs-string">"1"</span>, <span class="hljs-string">"2"</span>];
  <span class="hljs-keyword">return</span> ids.map(<span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> <span class="hljs-string">`/hoge/<span class="hljs-subst">${id}</span>`</span>);
}
</code></pre>
<p><a target="_blank" href="https://vike.dev/onBeforePrerenderStart">https://vike.dev/onBeforePrerenderStart</a></p>
<h2 id="heading-build">Build</h2>
<p>Run <code>vike build</code> to generate the HTML files:</p>
<pre><code class="lang-plaintext">./node_modules/.bin/vike build
...
✓ 3 HTML documents pre-rendered.
✓ built in 633ms
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Using Vite, Vike, and Vike-react, we were able to perform SSG for pages with dynamic IDs.<br />It was surprisingly straightforward, reaffirming how convenient this stack is.<br />However, Vike is still under active development, and small updates can cause warnings or break old setups.<br />We need to stay flexible and test things ourselves while adapting to changes.</p>
<p>I hope this article helps you get started with SSG for dynamic routes!</p>
<h2 id="heading-reference">Reference</h2>
<p>You can see this implementation live here:<br /><a target="_blank" href="https://nekometry.web.app/?utm_source=zenn.dev&amp;utm_medium=referral&amp;utm_campaign=article20250513">https://nekometry.web.app/</a></p>
<p>This article is an English translation of the original Japanese article available at <a target="_blank" href="https://zenn.dev/ara_ta3/articles/typescript-vike-ssg-with-dynamic-routing">https://zenn.dev/ara_ta3/articles/typescript-vike-ssg-with-dynamic-routing</a>.</p>
]]></content:encoded></item><item><title><![CDATA[How to Use Vike for SSG in a Vite, TypeScript, and React Project]]></title><description><![CDATA[Easily deploy to GitHub Pages]]></description><link>https://ara-ta3.hashnode.dev/typescript-vike-ssg-getting-started</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/typescript-vike-ssg-getting-started</guid><category><![CDATA[vite]]></category><category><![CDATA[vike]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[React]]></category><category><![CDATA[GitHubPages]]></category><category><![CDATA[ssg]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Thu, 22 May 2025 15:15:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747925981601/20732913-6d68-42e0-8faa-b02e90846cb5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<h2 id="heading-overview">Overview</h2>
<p>I wanted to host it on GitHub Pages, so I thought, why not try SSG while I'm at it.<br />While developing with Vite + TypeScript + React, I came across a library called Vike for SSG.<br />Originally, it seems to have been a Vite plugin called <code>vite-plugin-ssr</code>.</p>
<p><a target="_blank" href="https://vite-plugin-ssr.com/">https://vite-plugin-ssr.com/</a></p>
<blockquote>
<p>The vite-plugin-ssr project has been renamed Vike.</p>
</blockquote>
<p>This time, I’ll use Vike to generate static files from a page built with TypeScript + React.</p>
<p>Note: Although you can skip some parts by using the <code>vike-react</code> extension, I’m not using it here to better understand how Vike works.</p>
<p><a target="_blank" href="https://github.com/vikejs/vike-react">https://github.com/vikejs/vike-react</a></p>
<p>Here’s the repository with the code I used:</p>
<p><a target="_blank" href="https://github.com/ara-ta3/vike-ssg-getting-started">https://github.com/ara-ta3/vike-ssg-getting-started</a></p>
<p>The versions used for Vite, Vike, and React are:</p>
<pre><code class="lang-plaintext">"react": "19.0.0"
"react-dom": "19.0.0"
"vike": "0.4.210"
"vite": "6.0.5"
</code></pre>
<h1 id="heading-outputting-to-html">Outputting to HTML</h1>
<p>Let’s start with a basic Hello World.<br />Add settings in <code>vite.config.ts</code>, place some files under <code>pages</code> and <code>renderer</code> directories, and run <code>vite dev</code> to see Hello World.</p>
<h2 id="heading-setup-viteconfigts">Setup vite.config.ts</h2>
<p>Add Vike to plugins and set <code>prerender</code> to true.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">"vite"</span>;
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">"@vitejs/plugin-react"</span>;
<span class="hljs-keyword">import</span> vike <span class="hljs-keyword">from</span> <span class="hljs-string">"vike/plugin"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
  plugins: [react(), vike({ prerender: <span class="hljs-literal">true</span> })],
});
</code></pre>
<h2 id="heading-setup-srcpages-and-srcrenderer">Setup src/pages and src/renderer</h2>
<h3 id="heading-srcpages">src/pages</h3>
<p>Implement individual pages here.<br />Let’s put an <code>h1</code> with Hello World for now.<br />For more complex pages, you’ll call components here.<br />Place <code>+Page.tsx</code> under <code>src/pages/</code> to match URL <code>/</code>.<br />For <code>/hoge</code>, create <code>src/pages/hoge/+Page.tsx</code>.</p>
<pre><code class="lang-tsx">import React from "react";

export { Page };

function Page() {
  return (
    &lt;div&gt;
      &lt;h1&gt;Hello World&lt;/h1&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<h3 id="heading-srcrenderer">src/renderer</h3>
<p>Refer to the following to create <code>+onRenderClient.tsx</code> and <code>+onRenderHtml.tsx</code>.</p>
<p><a target="_blank" href="https://vike.dev/onRenderHtml%EF%BF%BChttps://vike.dev/onRenderClient%EF%BF%BChttps://github.com/vikejs/vike/tree/main/examples/react-minimal%EF%BF%BChttps://github.com/vikejs/vike/tree/main/examples/react-full">https://vike.dev/onRenderHtml<br />https://vike.dev/onRenderClient<br />https://github.com/vikejs/vike/tree/main/examples/react-minimal<br />https://github.com/vikejs/vike/tree/main/examples/react-full</a></p>
<p>These files are unnecessary if using <code>vike-react</code>.</p>
<p><a target="_blank" href="https://vike.dev/react">https://vike.dev/react</a></p>
<p>src/renderer/+onRenderClient.tsx</p>
<pre><code class="lang-tsx">import React from "react";
import ReactDOM from "react-dom/client";
import type { PageContextBuiltInClient } from "vike";

export { render as onRenderClient };

async function render(pageContext: PageContextBuiltInClient) {
  const { Page } = pageContext;
  const root = document.getElementById("root")!;
  const pageProps = "pageProps" in pageContext &amp;&amp; pageContext.pageProps;

  ReactDOM.hydrateRoot(
    root,
    &lt;React.StrictMode&gt;
      &lt;Page {...pageProps} /&gt;
    &lt;/React.StrictMode&gt;
  );
}
</code></pre>
<p>src/renderer/+onRenderHtml.tsx</p>
<pre><code class="lang-tsx">import React from "react";
import { renderToString } from "react-dom/server";
import { dangerouslySkipEscape, escapeInject } from "vike/server";

async function onRenderHtml(pageContext) {
  const { Page } = pageContext;
  const viewHtml = dangerouslySkipEscape(renderToString(&lt;Page /&gt;));
  const title = pageContext.config.title || "default title";
  const description = pageContext.config.description || "default description";

  return escapeInject`&lt;!DOCTYPE html&gt;
    &lt;html&gt;
        &lt;title&gt;${title}&lt;/title&gt;
        &lt;meta name="description" content="${description}"&gt;
        &lt;body&gt;
            &lt;div id="root"&gt;${viewHtml}&lt;/div&gt;
        &lt;/body&gt;
    &lt;/html&gt;`;
}
export default onRenderHtml;
</code></pre>
<p>Directory and file structure:</p>
<pre><code class="lang-bash">tree -I node_modules -I dist
.
├── package-lock.json
├── package.json
├── src
│   ├── pages
│   │   └── +Page.tsx
│   └── renderer
│       ├── +onRenderClient.tsx
│       └── +onRenderHtml.tsx
├── tsconfig.json
└── vite.config.ts
</code></pre>
<h1 id="heading-add-a-new-page-under-srcpages">Add a New Page Under src/pages</h1>
<p>Let’s add a page at <code>/hoge</code>.<br />Just add <code>+Page.tsx</code> in <code>src/pages/hoge</code>.</p>
<pre><code class="lang-tsx">import React from "react";

export { Page };

function Page() {
  return (
    &lt;div&gt;
      &lt;h1&gt;This is hoge page&lt;/h1&gt;
      &lt;a href="/"&gt;to root&lt;/a&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>Directory structure:</p>
<pre><code class="lang-bash">tree -I node_modules -I dist
.
├── package-lock.json
├── package.json
├── src
│   ├── pages
│   │   ├── +Page.tsx
│   │   └── hoge
│   │       └── +Page.tsx
│   └── renderer
│       ├── +onRenderClient.tsx
│       └── +onRenderHtml.tsx
├── tsconfig.json
└── vite.config.ts
</code></pre>
<p>Nice and simple.</p>
<h1 id="heading-customize-title-tag-per-url">Customize Title Tag per URL</h1>
<p>If you're doing SSG, you’ll want meta tags like the title to vary by URL.<br />In <code>src/renderer/+config.ts</code>, add config to support <code>title</code>, then set the title in <code>src/pages/+config.ts</code>.</p>
<p>Also, <code>src/renderer/+onRenderHtml.tsx</code> already fetches <code>pageContext.config.title</code> for the head tag.</p>
<p>src/renderer/+config.ts</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> <span class="hljs-keyword">type</span> { Config } <span class="hljs-keyword">from</span> <span class="hljs-string">"vike/types"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> config = {
  meta: {
    title: {
      env: { server: <span class="hljs-literal">true</span>, client: <span class="hljs-literal">true</span> },
    },
    description: {
      env: { server: <span class="hljs-literal">true</span>, client: <span class="hljs-literal">true</span> },
    },
  },
} satisfies Config;
</code></pre>
<p>src/pages/+config.ts</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  title: <span class="hljs-string">"title from config"</span>,
  description: <span class="hljs-string">"description from config"</span>,
};
</code></pre>
<p>Run <code>vite build</code> and check <code>dist/client/index.html</code>, you’ll see the title set.</p>
<pre><code class="lang-bash">cat dist/client/index.html|grep title
        &lt;title&gt;title from config&lt;/title&gt;
</code></pre>
<h1 id="heading-simplify-renderer-with-vike-react">Simplify Renderer with vike-react</h1>
<p>Although not shown in the original repo, using the <code>vike-react</code> extension eliminates the need for the <code>renderer</code> directory entirely.<br />Just run <code>npm install vike-react</code> and add an <code>extends</code> field in <code>src/pages/+config.ts</code>.</p>
<p>src/pages/+config.ts</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> vikeReact <span class="hljs-keyword">from</span> <span class="hljs-string">"vike-react/config"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  <span class="hljs-keyword">extends</span>: [vikeReact],
  title: <span class="hljs-string">"title from config"</span>,
  description: <span class="hljs-string">"description from config"</span>,
};
</code></pre>
<p>Directory structure:</p>
<pre><code class="lang-bash">tree -I node_modules -I dist
.
├── package-lock.json
├── package.json
├── src
│   └── pages
│       ├── +Page.tsx
│       ├── +config.ts
│       └── hoge
│           └── +Page.tsx
├── tsconfig.json
└── vite.config.ts
</code></pre>
<h1 id="heading-summary">Summary</h1>
<ul>
<li><p>Used Vike and Vite to statically generate a React app</p>
</li>
<li><p>Easy configuration makes SSG very convenient</p>
</li>
</ul>
<h2 id="heading-side-note-deploying-to-github-pages">(Side Note) Deploying to GitHub Pages</h2>
<p>After running <code>vite build</code>, host the <code>dist/client</code> directory to deploy to GitHub Pages.</p>
<h2 id="heading-references">References</h2>
<p>Originally written in Japanese and published on Zenn: <a target="_blank" href="https://zenn.dev/ara_ta3/articles/typescript-vike-ssg-getting-started">https://zenn.dev/ara_ta3/articles/typescript-vike-ssg-getting-started</a></p>
<p><a target="_blank" href="https://zenn.dev/ara_ta3/articles/typescript-vike-ssg-getting-started">Used in the following sites:</a></p>
<h3 id="heading-nekometryhttpszenndevarata3articlestypescript-vike-ssg-getting-started"><a target="_blank" href="https://zenn.dev/ara_ta3/articles/typescript-vike-ssg-getting-started">Nekometry</a></h3>
<p><a target="_blank" href="https://zenn.dev/ara_ta3/articles/typescript-vike-ssg-getting-started">https://nekometry.web.app/</a></p>
<h3 id="heading-personal-site">Personal Site</h3>
<p><a target="_blank" href="https://github.com/ara-ta3/ara-ta3.github.io%EF%BF%BChttps://ara-ta3.github.io/">https://github.com/ara-ta3/ara-ta3.github.io<br />https://ara-ta3.github.io/</a></p>
]]></content:encoded></item><item><title><![CDATA[🦙Building a Local ChatGPT-like Environment with Ollama and Open WebUI on Ubuntu🦙]]></title><description><![CDATA[This article serves as a personal memo on how to set up a local ChatGPT-like conversational environment using Ollama and Open WebUI on an Ubuntu…]]></description><link>https://ara-ta3.hashnode.dev/ollama-openwebui-getting-started</link><guid isPermaLink="true">https://ara-ta3.hashnode.dev/ollama-openwebui-getting-started</guid><category><![CDATA[ollama]]></category><category><![CDATA[open-webui]]></category><category><![CDATA[Ubuntu]]></category><dc:creator><![CDATA[ara-ta3]]></dc:creator><pubDate>Wed, 21 May 2025 16:45:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747877135925/13255221-250e-4ce1-926b-9085225e387b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<h2 id="heading-introduction">Introduction</h2>
<p>This article serves as a personal memo on how to set up a local ChatGPT-like conversational environment using <strong>Ollama</strong> and <strong>Open WebUI</strong> on an Ubuntu system.<br />Ollama is a tool that allows you to run various LLMs (Large Language Models) locally, and Open WebUI provides a web-based interface to interact with Ollama.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>The following setup was verified on:</p>
<p>Although I mention "Ubuntu," I'm actually running it on a low-end <strong>Mac mini 2018</strong> with Ubuntu installed—so the specs are quite modest.</p>
<pre><code class="lang-bash">lsb_release -d
Description:    Ubuntu 24.04 LTS
</code></pre>
<pre><code class="lang-bash">ollama --version
ollama version is 0.6.8
</code></pre>
<h2 id="heading-setup-steps">Setup Steps</h2>
<h3 id="heading-1-install-ollama">1. Install Ollama</h3>
<p>First, install Ollama using the following command:</p>
<pre><code class="lang-bash">curl -L https://ollama.ai/install.sh | bash
</code></pre>
<p>After installation, check if it works:</p>
<pre><code class="lang-bash">ollama --version
</code></pre>
<p>You can find models at <a target="_blank" href="http://ollama.com">ollama.com</a>, and download or run them with commands like:</p>
<pre><code class="lang-bash">ollama pull &lt;model_name&gt;
ollama run &lt;model_name&gt;
</code></pre>
<p>Example:</p>
<pre><code class="lang-bash">ollama pull phi4
ollama run phi4

ollama pull gemma3
ollama run gemma3
</code></pre>
<h3 id="heading-2-run-open-webui">2. Run Open WebUI</h3>
<p>To start Open WebUI, run the following Docker command:</p>
<pre><code class="lang-bash">docker run -d -p 3000:8080  --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data ghcr.io/open-webui/open-webui:main
</code></pre>
<h3 id="heading-25-if-docker-cannot-connect-to-ollama">2.5. If Docker Cannot Connect to Ollama</h3>
<p>In my case, Open WebUI inside Docker couldn’t connect to Ollama directly, so I tested connectivity using <code>curl</code> from inside the container.</p>
<ol>
<li>Check if the container can reach Ollama:</li>
</ol>
<pre><code class="lang-bash">docker run --rm curlimages/curl http://172.17.0.1:11434
</code></pre>
<ol start="2">
<li>If not reachable, modify Ollama settings to allow external connections.</li>
</ol>
<p>Edit <code>/etc/systemd/system/ollama.service</code> and add the following:</p>
<pre><code class="lang-bash">Environment=<span class="hljs-string">"OLLAMA_HOST=0.0.0.0"</span>
</code></pre>
<p>You can also run the server directly like this for testing:</p>
<pre><code class="lang-bash">OLLAMA_HOST=0.0.0.0 ollama serve
</code></pre>
<p>Then reload and restart the service:</p>
<pre><code class="lang-bash">sudo systemctl daemon-reload
sudo systemctl restart ollama
</code></pre>
<p>Note: Setting <code>OLLAMA_HOST=0.0.0.0</code> exposes Ollama to all external connections, which is suitable for debugging but <strong>not recommended for production</strong>. Please secure it appropriately.</p>
<h3 id="heading-3-using-open-webui">3. Using Open WebUI</h3>
<p>Once Open WebUI is running, open your browser and navigate to <a target="_blank" href="http://localhost:3000.%EF%BF%BCYou%E2%80%99ll"><code>http://localhost:3000</code>.<br />You’ll</a> be able to select models already downloaded via Ollama and start chatting through the browser interface.</p>
<h2 id="heading-conclusion-amp-thoughts">Conclusion &amp; Thoughts</h2>
<p>In this article, I explained how to install <strong>Ollama</strong> and <strong>Open WebUI</strong> on Ubuntu to create a local ChatGPT-like experience.<br />Since I ran this on a relatively underpowered machine, performance was predictably modest—the responses were slow and the models weren't particularly "smart."</p>
<p>I’ve started to explore the Agent mode feature, but so far I wouldn’t say it’s ready for serious use.<br />Still, I'm curious about potential fun use cases and plan to experiment more.</p>
<p>Note: This article is an English translation of my original post published in Japanese on Zenn: <a target="_blank" href="https://zenn.dev/ara_ta3/articles/ollama-openwebui-getting-started">https://zenn.dev/ara_ta3/articles/ollama-openwebui-getting-started</a></p>
]]></content:encoded></item></channel></rss>