add help arg
[cedit] / cedit
1 #!/bin/bash
2 # Copyright (C) 2016 Ian Kelling
3
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 cedit() {
17 local help="Usage: [-h|--help ] [-v] [SECTION_NAME] FILE
18 Create/edit a #comment delimited section of a file
19
20 Reads STDIN for the contents of the section. Without SECTION_NAME, it
21 acts on a global unnamed section. cedit is short for config edit.
22
23 -v Verbose
24 -h|--help Help"
25 local s diff name init
26 local file_dir="$(dirname "$file")"
27 local exists=true
28 local verbose=false
29
30 case $1 in
31 -h|--help) echo "$help"; return ;;
32 esac
33
34 if [[ $1 == -v ]]; then
35 verbose=true
36 shift
37 fi
38 if (( $# == 2 )); then
39 name=": $1"
40 shift
41 fi
42
43 local file="$1"
44 local file_name="${file##*/}"
45
46 local begin="#_#_# start delimiter of cedit section$name. do not modify. #_#_#"
47 local end="#_#_# end delimiter of cedit section$name. do not modify. #_#_#"
48
49 if [[ ! -e $file_dir ]]; then
50 if ! mkdir -p $file_dir; then
51 s=sudo
52 $s mkdir -p $file_dir || return 1
53 fi
54 fi
55 if [[ ! -e $file ]]; then
56 exists=false
57 if ! $s touch $file; then
58 s=sudo
59 $s touch $file || return 1
60 fi
61 fi
62
63 [[ -w $file ]] || s=sudo
64
65
66 if $exists; then
67 local temp="$(mktemp -d)/$file_name"
68 cp "$file" "$temp"
69 cp /dev/null "$file"
70 local in_section=false
71 while IFS= read -r line; do
72 if [[ $line == $begin ]]; then
73 in_section=true;
74 fi
75 if ! $in_section; then
76 printf '%s\n' "$line" >> $file
77 fi
78 if [[ $line == $end ]]; then
79 in_section=false;
80 fi
81 done < "$temp"
82 fi
83
84 IFS= read -d '' -n 1 -r init
85 if [[ $init ]]; then
86 $s tee -a "$file" >/dev/null <<<"$begin"
87 printf '%s' "$init" | $s tee -a "$file" >/dev/null
88 $s tee -a "$file" >/dev/null
89 $s tee -a "$file" >/dev/null <<<"$end"
90 fi
91
92 if ! $exists; then
93 ret=0
94 if $verbose; then
95 echo "New file $file:"
96 cat "$file"
97 fi
98 elif type -t diff &>/dev/null; then
99 diff=$(diff -u "$temp" "$file")
100 ret=$?
101 if $verbose; then
102 if (( $ret == 0 )); then
103 echo "No changes made to $file"
104 fi
105 else
106
107 echo "backup of original at $temp"
108 echo diff -u "$temp" "$file":
109 echo "$diff"
110 fi
111 else
112 diff=$(cmp "$temp" "$file")
113 ret=$?
114 if $verbose; then
115 echo "$diff"
116 fi
117 fi
118 return $ret
119 }
120 cedit "$@"