1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.jclouds.scriptbuilder.domain;
20
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static com.google.common.base.Preconditions.checkState;
23 import static org.jclouds.scriptbuilder.domain.Statements.interpret;
24
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29
30 import com.google.common.collect.ImmutableList;
31 import com.google.common.collect.Iterables;
32 import com.google.common.collect.Lists;
33 import com.google.common.collect.Maps;
34
35
36
37
38
39
40 public class AppendFile implements Statement {
41 public static final String MARKER = "END_OF_FILE";
42
43 final String path;
44 final Iterable<String> lines;
45 final String marker;
46
47 public AppendFile(String path, Iterable<String> lines) {
48 this(path, lines, MARKER);
49 }
50
51 public AppendFile(String path, Iterable<String> lines, String marker) {
52 this.path = checkNotNull(path, "path");
53 this.lines = checkNotNull(lines, "lines");
54 this.marker = checkNotNull(marker, "marker");
55 checkState(Iterables.size(lines) > 0, "you must pass something to execute");
56 }
57
58 public static String escapeVarTokens(String toEscape, OsFamily family) {
59 Map<String, String> inputToEscape = Maps.newHashMap();
60 for (ShellToken token : ImmutableList.of(ShellToken.VARL, ShellToken.VARR)) {
61 if (!token.to(family).equals("")) {
62 String tokenS = "{" + token.toString().toLowerCase() + "}";
63 inputToEscape.put(tokenS, "{escvar}" + tokenS);
64 }
65 }
66 for (Entry<String, String> entry : inputToEscape.entrySet()) {
67 toEscape = toEscape.replace(entry.getKey(), entry.getValue());
68 }
69 return toEscape;
70 }
71
72 @Override
73 public Iterable<String> functionDependencies(OsFamily family) {
74 return Collections.emptyList();
75 }
76
77 @Override
78 public String render(OsFamily family) {
79 List<Statement> statements = Lists.newArrayList();
80 if (family == OsFamily.UNIX) {
81 StringBuilder builder = new StringBuilder();
82 hereFile(path, builder);
83 statements.add(interpret(builder.toString()));
84 } else {
85 for (String line : lines) {
86 statements.add(appendToFile(line, path, family));
87 }
88 }
89 return new StatementList(statements).render(family);
90 }
91
92 protected void hereFile(String path, StringBuilder builder) {
93 builder.append("cat >> ").append(path).append(" <<'").append(marker).append("'\n");
94 for (String line : lines) {
95 builder.append(line).append("\n");
96 }
97 builder.append(marker).append("\n");
98 }
99
100 protected Statement appendToFile(String line, String path, OsFamily family) {
101 String quote = "";
102 if (!ShellToken.VQ.to(family).equals("")) {
103 quote = "'";
104 } else {
105 line = escapeVarTokens(line, family);
106 }
107 return interpret(String.format("echo %s%s%s >>%s{lf}", quote, line, quote, path));
108 }
109
110 }