Replace switch orphan branch shell script with a Ruby program

This commit is contained in:
Gabriel Arazas 2023-04-04 23:06:16 +08:00
parent 3d19d1a2d2
commit b2944ef75f
No known key found for this signature in database
GPG Key ID: ADE0C41DAB221FCC
2 changed files with 54 additions and 7 deletions

View File

@ -1,7 +0,0 @@
#!/usr/bin/env nix-shell
#! nix-shell -p findutils coreutils git fzf -i bash
find ./content/ -mindepth 2 -iname 'index.adoc' -printf '%P\n' \
| xargs dirname \
| fzf --prompt "Choose orphan content branch " --filepath-word --info=hidden \
| xargs git switch --orphan

View File

@ -0,0 +1,54 @@
#!/usr/bin/env nix-shell
#! nix-shell -i ruby -p "ruby.withPackages (ps: with ps; [ rugged ])" coreutils fzf
# frozen_string_literal: true
require 'fileutils'
require 'logger'
require 'optparse'
require 'rugged'
CONTENT_DIRECTORY = 'content'
options = {
prefix: 'posts/',
repo: './code-workspace'
}
logger = Logger.new($stdout)
logger.level = Logger::WARN
OptionParser.new do |opts|
opts.on('-p', '--prefix PREFIX',
<<~HELP
Sets the prefix corresponding to a subdirectory inside
the content directory.
HELP
) do |prefix|
options[:prefix] = prefix
end
opts.on('--repo REPO', 'The repository location.') do |repo|
options[:repo] = repo
end
opts.on('-v', '--[no-]verbose', 'Make the program print results') do |v|
options[:verbose] = v
end
end.parse!
logger.level = Logger::INFO if options[:verbose]
initial_path = File.expand_path(options[:prefix], CONTENT_DIRECTORY)
files = Dir.new(initial_path)
.children
.select do |file|
path = File.expand_path(file, initial_path)
File.directory? path
end
.map { |file| File.join options[:prefix], file }
.sort
selected_branch = `echo -e "#{files.join '\n'}" | fzf`.strip
code_workspace = Rugged::Repository.discover(options[:repo])
code_workspace.head=("refs/heads/#{selected_branch}")
logger.info "Switched '#{options[:repo]}' to orphan branch '#{code_workspace}'"