Skip to content

Add simple generic utlity for asserting workspace version information during platform startup

Something like this:

	public static Path getWorkspacePath() {
		IPath finalPath = Platform.getLocation();
		if (finalPath == null)
			throw new IllegalStateException("No workspace (-data) defined for current runtime, cannot resolve workspace path");
		return finalPath.toFile().toPath();
	}

	private static String message(Path ws, String expectedVersion, String gotVersion) {
		StringBuilder sb = new StringBuilder();
		sb.append("The workspace at ").append(ws.toAbsolutePath().toString()) //$NON-NLS-1$
		.append(" is incompatible with this program version:\n") //$NON-NLS-1$
		.append(expectedVersion);
		if (!gotVersion.isEmpty())
			sb.append("\n\nWorkspace version is:\n") //$NON-NLS-1$
			.append(gotVersion);
		sb.append("\n\nThe program will now close."); //$NON-NLS-1$
		return sb.toString();
	}

	public static String validateWorkspaceVersion(String... expectedVersionDescriptor) throws IOException {
		Path ws = getWorkspacePath();
		Path ver = ws.resolve(".version"); //$NON-NLS-1$
		return validateWorkspaceVersion(ws, ver, expectedVersionDescriptor);
	}

	public static String validateWorkspaceVersion(Path workspace, Path versionFile, String... expectedVersionDescriptor) throws IOException {
		Charset utf = StandardCharsets.UTF_8;
		try {
			List<String> lines = Files.readAllLines(versionFile, utf);
			boolean ok = true;
			if (lines.size() >= expectedVersionDescriptor.length) {
				for (int i = 0; i < expectedVersionDescriptor.length; ++i) {
					String got = lines.get(i);
					String expected = expectedVersionDescriptor[i];
					if (!got.equals(expected)) {
						ok = false;
						break;
					}
				}
			} else {
				ok = false;
			}
			return ok ?  null : message(workspace, EString.implode(expectedVersionDescriptor, "\n"), EString.implode(lines, "\n")); //$NON-NLS-1$ //$NON-NLS-2$
		} catch (NoSuchFileException e) {
			Files.write(versionFile, Arrays.asList(expectedVersionDescriptor), utf);
			return null;
		}
	}
Edited by Tuukka Lehtonen