File tree Expand file tree Collapse file tree 4 files changed +88
-2
lines changed Expand file tree Collapse file tree 4 files changed +88
-2
lines changed Original file line number Diff line number Diff line change @@ -3,8 +3,8 @@ organisation: "moremoban"
33author : " chfw"
4455company : " C.W."
6- version : " 0.0.1 "
7- current_version : " 0.0.1 "
6+ version : " 0.0.2 "
7+ current_version : " 0.0.2 "
88release : " 0.0.1"
99copyright_year : 2020
1010license : newbsd
Original file line number Diff line number Diff line change 1+ import re
2+
3+ from moban .core .content_processor import ContentProcessor
4+
5+
6+ @ContentProcessor ("lineinfile" , "Checking" , "Checked" )
7+ def line_in_file (content : str , options : dict ) -> str :
8+ regexp = options .get ("regexp" )
9+ create = options .get ("create" , False )
10+ state = options .get ("state" , "present" )
11+
12+ lines = content .split ("\n " )
13+
14+ if state == "present" :
15+ if regexp :
16+ lines = present (lines , options )
17+ elif create :
18+ # regexp is None or ''
19+ # append the line to the end
20+ line = options .get ("line" )
21+ if line :
22+ lines += [line ]
23+
24+ else :
25+ lines = list (absent (lines , options ))
26+
27+ return "\n " .join (lines )
28+
29+
30+ def present (lines , options ):
31+ ensure_line = options .get ("line" )
32+ regexp = options ["regexp" ]
33+
34+ for line in lines :
35+ if re .match (regexp , line ):
36+ yield ensure_line
37+ else :
38+ yield line
39+
40+
41+ def absent (lines , options ):
42+ regexp = options ["regexp" ]
43+
44+ for line in lines :
45+ if re .match (regexp , line ):
46+ continue
47+
48+ yield line
Original file line number Diff line number Diff line change 1+ from nose .tools import eq_
2+
3+ from moban_ansible .engines .line_in_file import line_in_file
4+
5+
6+ def test_append_a_line ():
7+ options = {"create" : "yes" , "line" : "192.168.1.1 foo.bar foo" }
8+
9+ content = "127.0.0.1 localhost"
10+
11+ new_content = line_in_file (content , options )
12+ expected = [content , options ["line" ]]
13+
14+ eq_ (new_content , "\n " .join (expected ))
15+
16+
17+ def test_absent ():
18+ absent_line = "192.168.1.1 foo.bar foo"
19+ options = {"regexp" : ".*foo$" , "state" : "absent" }
20+
21+ content = f"127.0.0.1 localhost\n { absent_line } "
22+
23+ new_content = line_in_file (content , options )
24+ expected = "127.0.0.1 localhost"
25+
26+ eq_ (new_content , expected )
27+
28+
29+ def test_present ():
30+ present_line = "192.168.1.1 foo.bar foo"
31+ options = {"regexp" : ".*foo$" , "line" : present_line }
32+
33+ content = f"127.0.0.1 localhost\n 192.162.1.1 foo"
34+
35+ new_content = line_in_file (content , options )
36+ expected = ["127.0.0.1 localhost" , present_line ]
37+
38+ eq_ (new_content , "\n " .join (expected ))
You can’t perform that action at this time.
0 commit comments