View Javadoc

1   package de.matthias_burbach.mosaique.core.util;
2   
3   import java.util.regex.Matcher;
4   import java.util.regex.Pattern;
5   
6   /***
7    * Is a simple interface to the SCM tool Perforce (short: P4).
8    *
9    * @author Matthias Burbach
10   */
11  public class P4 {
12      /***
13       * @return <code>true</code> if the Perforce command line can be accessed
14       *         by this class.
15       */
16      public boolean isP4Installed() {
17          CommandLine cl = new CommandLine();
18          int exitCode = cl.execute("p4");
19          boolean result = (exitCode == 0) && cl.getStdErr().length() == 0;
20          return result;
21      }
22  
23      /***
24       * @param file The file to check.
25       * @return <code>true</code> if the file is under Perforce control
26       *         (also if only opened for add yet).
27       */
28      public boolean isP4Controlled(final String file) {
29          CommandLine cl = new CommandLine();
30          int exitCode = cl.execute("p4 fstat " + file);
31          boolean result = (exitCode == 0) && cl.getStdErr().length() == 0;
32          return result;
33      }
34  
35      /***
36       * @param file The file to get the synched revision for.
37       * @return The revision of the file that is currently synched on the client.
38       *         Returns -1 if no revision is synched or if Perforce access
39       *         failed.
40       */
41      public int getSynchedRevision(final String file) {
42          CommandLine cl = new CommandLine();
43          int exitCode = cl.execute("p4 have " + file);
44          int result = -1;
45          if (exitCode == 0 && cl.getStdErr().length() == 0) {
46              /*
47               * Try to parse the revision number from the stdout output.
48               */
49              String output = cl.getStdoutWithoutNewLines();
50              Matcher matcher =
51                  Pattern.compile(".*#([0-9]+) - .*").matcher(output);
52              if (matcher.matches()) {
53                  String revision = matcher.group(1);
54                  try {
55                      result = Integer.parseInt(revision);
56                  } catch (Exception e) {
57                      e.printStackTrace();
58                  }
59              }
60          }
61          return result;
62      }
63  
64      /***
65       * @param file The file to check.
66       * @return <code>true</code> if the file is now opened for edit.
67       */
68      public boolean openForEdit(final String file) {
69          CommandLine cl = new CommandLine();
70          int exitCode = cl.execute("p4 edit " + file);
71          boolean result = (exitCode == 0) && cl.getStdErr().length() == 0;
72          return result;
73      }
74  }