aboutsummaryrefslogtreecommitdiff
path: root/functions/rencase.fish
blob: b0f691a32f59425bffd06e0d2cf0cad900f2abf8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
function rencase --description 'Change the case of all files and directories'

function _print_option -a opt -a desc
  printf "\t%-20s %s\n" $opt $desc
end

function _display_help
  echo "usage: rencase <option> [files...]"
  echo
  _print_option "-l,--low" "Rename files to lowercase (default)"
  _print_option "-h,--high" "Rename files to uppercase"
  _print_option "-n,--nodir" "Don't rename directories"
  echo
end

function _low_or_high -a mode -a str
  switch $mode
    case low
      echo (string lower $str)
    case high
      echo (string upper $str)
  end
end

if not argparse 'l/low' 'h/high' 'n/nodir' -- $argv
  _display_help
  return 1
end

if set -q _flag_low; and set -q _flag_high
  echo "--low and --high are mutually exclusive options."
  echo
  _display_help
  return 1
end

set mode 'low'

if set -q _flag_high
  set mode 'high'
end

if test (count $argv) -gt 0
  set targets $argv
else
  set targets '.'
end

for file in (find $targets -type f)
  set -l element (string split -r -m1 / $file)
  set -l newname (_low_or_high $mode $element[2])
  if test -e $element[1]/$newname
    set_color red
    echo "File $newname already exists. Skipping."
    set_color normal
    continue
  end
  mv -- "$file" "$element[1]/$newname"
end

if not set -q _flag_nodir
  set -f dirs (find $targets -type d)
  for dir in $dirs[-1..1] # Rename directories in reverse order
    set -l element (string split -r -m1 / $dir)
    set -l newname (_low_or_high $mode $element[2])
    if not test -z $element[2]; and not test -e $element[1]/$newname # Also catch .
      mv -- "$dir" "$element[1]/$newname"
    else
      set_color red
      echo "Directory $element[2] already exists. Skipping."
      set_color normal
    end
  end
end

functions -e _print_option
functions -e _display_help
functions -e _low_or_high

end