good working version
[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() { # [-v] [section_name] FILE
17
18 local s diff name init
19 local file_dir="$(dirname "$file")"
20 local exists=true
21 local verbose=false
22
23 if [[ $1 == -v ]]; then
24 verbose=true
25 shift
26 fi
27 if (( $# == 2 )); then
28 name=": $1"
29 shift
30 fi
31
32 local file="$1"
33 local file_name="${file##*/}"
34
35 local begin="#_#_# start delimiter of cedit section$name. do not modify. #_#_#"
36 local end="#_#_# end delimiter of cedit section$name. do not modify. #_#_#"
37
38 if [[ ! -e $file_dir ]]; then
39 if ! mkdir -p $file_dir; then
40 s=sudo
41 $s mkdir -p $file_dir || return 1
42 fi
43 fi
44 if [[ ! -e $file ]]; then
45 exists=false
46 if ! $s touch $file; then
47 s=sudo
48 $s touch $file || return 1
49 fi
50 fi
51
52 [[ -w $file ]] || s=sudo
53
54
55 if $exists; then
56 local temp="$(mktemp -d)/$file_name"
57 cp "$file" "$temp"
58 cp /dev/null "$file"
59 local in_section=false
60 while IFS= read -r line; do
61 if [[ $line == $begin ]]; then
62 in_section=true;
63 fi
64 if ! $in_section; then
65 printf '%s\n' "$line" >> $file
66 fi
67 if [[ $line == $end ]]; then
68 in_section=false;
69 fi
70 done < "$temp"
71 fi
72
73 IFS= read -d '' -n 1 -r init
74 if [[ $init ]]; then
75 $s tee -a "$file" >/dev/null <<<"$begin"
76 printf '%s' "$init" | $s tee -a "$file" >/dev/null
77 $s tee -a "$file" >/dev/null
78 $s tee -a "$file" >/dev/null <<<"$end"
79 fi
80
81 if ! $exists; then
82 ret=0
83 if $verbose; then
84 echo "New file $file:"
85 cat "$file"
86 fi
87 elif type -t diff &>/dev/null; then
88 diff=$(diff -u "$temp" "$file")
89 ret=$?
90 if $verbose; then
91 if (( $ret == 0 )); then
92 echo "No changes made to $file"
93 fi
94 else
95
96 echo "backup of original at $temp"
97 echo diff -u "$temp" "$file":
98 echo "$diff"
99 fi
100 else
101 diff=$(cmp "$temp" "$file")
102 ret=$?
103 if $verbose; then
104 echo "$diff"
105 fi
106 fi
107 return $ret
108 }
109 cedit "$@"