|
| 1 | +package jason.cli.app; |
| 2 | + |
| 3 | +import picocli.CommandLine; |
| 4 | +import picocli.CommandLine.Command; |
| 5 | + |
| 6 | +import java.io.*; |
| 7 | + |
| 8 | + |
| 9 | +@Command( |
| 10 | + name = "add-agent", |
| 11 | + description = "adds a new agent into the application" |
| 12 | +) |
| 13 | +public class AddAgent extends Common implements Runnable { |
| 14 | + |
| 15 | + @CommandLine.Parameters(paramLabel = "<agent name>", defaultValue = "", |
| 16 | + arity = "1") |
| 17 | + String agName; |
| 18 | + |
| 19 | + |
| 20 | + @CommandLine.ParentCommand |
| 21 | + protected Application parent; |
| 22 | + |
| 23 | + @Override |
| 24 | + public void run() { |
| 25 | + if (agName.isEmpty()) { |
| 26 | + parent.parent.errorMsg("the name of the agent should be informed, e.g., 'app add-agent karlos'."); |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + try { |
| 31 | + var file = getProjectFile(""); |
| 32 | + if (file == null) { |
| 33 | + parent.parent.errorMsg("can not find a .mas2j file in the current directory!"); |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + var agFile = new File("src/agt/"+agName+".asl"); |
| 38 | + if (agFile.exists()) { |
| 39 | + parent.parent.errorMsg("a file '"+agFile+"' exists already, chose another name for the agent."); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + Create.copyFile("", "agent", agName, agFile, true); |
| 44 | + addAgInProject(file, agName); |
| 45 | + parent.parent.println("agent "+agName+" ("+agFile+") was included in "+file); |
| 46 | + } catch(Exception e) { |
| 47 | + parent.parent.errorMsg("error adding agent:\n" + e); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + private void addAgInProject(File file, String agName) { |
| 52 | + // read and change |
| 53 | + var text = new StringBuilder(); |
| 54 | + try (var in = new BufferedReader(new FileReader(file) )) { |
| 55 | + String l = in.readLine(); |
| 56 | + while (l != null) { |
| 57 | + if (l.contains("agents:")) |
| 58 | + l = l.replace("agents: ", "agents: "+agName+";\n "); |
| 59 | + text.append(l+"\n"); |
| 60 | + l = in.readLine(); |
| 61 | + } |
| 62 | + } catch (IOException e) { |
| 63 | + e.printStackTrace(); |
| 64 | + } |
| 65 | + |
| 66 | + // write |
| 67 | + try (var out = new BufferedWriter(new FileWriter(file))) { |
| 68 | + out.append(text.toString()); |
| 69 | + } catch (IOException e) { |
| 70 | + e.printStackTrace(); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | + |
0 commit comments