Skip to content

Automatically open the last session #478

@jakob1379

Description

@jakob1379

I made this wrapper, which in essence just saves the latest session id in a .droid file. If such a file exists this file will be used unless the -n|--new flag is used. That way I do not manually have to search for the last session in the project.

I would probably prefer this to be in the root of a git project, otherwise, just where droid is launched.

I might have overdone it a bit in terms of splitting it up, but the idea I still like. So what I propose is a similar functionality builtin to droid cli, e.g. just let it be a config setting the behaviour

#!/usr/bin/env bash

# Constants
readonly SESSION_FILE=".droid"
readonly SESSION_PATTERN='droid --resume [a-f0-9-]*'

# Cleanup temporary files on exit
cleanup() {
  local exit_code=$?
  [[ -n "${stderr_file:-}" && -f "$stderr_file" ]] && rm -f "$stderr_file"
  return "$exit_code"
}
trap cleanup EXIT

# Extract session ID from stderr output
extract_session_id() {
  local stderr_file="$1"

  if ! grep -q "$SESSION_PATTERN" "$stderr_file"; then
    return 1
  fi

  grep -o "$SESSION_PATTERN" "$stderr_file" | \
    sed 's/droid --resume //'
}

# Save session ID to file
save_session_id() {
  local session_id="$1"
  echo "$session_id" > "$SESSION_FILE"
}

# Load session ID from file, clean up if empty
load_session_id() {
  [[ ! -f "$SESSION_FILE" ]] && return 1

  local session_id
  session_id=$(cat "$SESSION_FILE" | tr -d '[:space:]')

  if [[ -z "$session_id" ]]; then
    rm -f "$SESSION_FILE"
    return 1
  fi

  echo "$session_id"
}

# Main execution
main() {
  local stderr_file
  local session_id
  local force_new_session=false
  local droid_args=()

  # Simple argument parsing
  for arg in "$@"; do
    case "$arg" in
      -n|--new)
        force_new_session=true
        ;;
      *)
        droid_args+=("$arg")
        ;;
    esac
  done

  stderr_file=$(mktemp)

  # Attempt to resume existing session
  if [[ "$force_new_session" == false ]] && session_id=$(load_session_id); then
    echo "Resuming droid session: $session_id"
    droid --resume "$session_id" "${droid_args[@]}" 2>"$stderr_file"
  else
    droid "${droid_args[@]}" 2>"$stderr_file"
  fi

  # Extract and persist any new session ID
  if new_session_id=$(extract_session_id "$stderr_file"); then
    save_session_id "$new_session_id"
    echo "Session ID saved: $new_session_id" >&2
  fi
}

main "$@"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions