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