From b2944ef75f86ea8ded056678bf94354a1acdcd3d Mon Sep 17 00:00:00 2001 From: Gabriel Arazas Date: Tue, 4 Apr 2023 23:06:16 +0800 Subject: [PATCH] Replace switch orphan branch shell script with a Ruby program --- bin/switch-content-orphan-branch | 7 ---- bin/switch-content-orphan-branch.rb | 54 +++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 7 deletions(-) delete mode 100644 bin/switch-content-orphan-branch create mode 100644 bin/switch-content-orphan-branch.rb diff --git a/bin/switch-content-orphan-branch b/bin/switch-content-orphan-branch deleted file mode 100644 index 65c478c..0000000 --- a/bin/switch-content-orphan-branch +++ /dev/null @@ -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 diff --git a/bin/switch-content-orphan-branch.rb b/bin/switch-content-orphan-branch.rb new file mode 100644 index 0000000..b3bd184 --- /dev/null +++ b/bin/switch-content-orphan-branch.rb @@ -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}'"