blob: 2427958840f361a4a141e530baa1d1385cd33885 [file] [log] [blame]
/*
* Copyright (c) 2012 Google Inc.
*
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
* Public License v1.0 which accompanies this distribution, and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.google.eclipse.protobuf.cdt.actions;
import static org.eclipse.xtext.util.Strings.isEmpty;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.internal.ui.editor.CEditor;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.ui.IEditorPart;
import com.google.inject.Singleton;
/**
* @author alruiz@google.com (Alex Ruiz)
*/
@SuppressWarnings("restriction")
@Singleton class ProtoFilePathFinder {
private static final Pattern PROTO_PATH_PATTERN = Pattern.compile("// source: (.*)");
IPath findProtoFilePathIn(IEditorPart editor) {
CEditor cEditor = (CEditor) editor;
String contents = contentsOf(cEditor);
if (isEmpty(contents)) {
return null;
}
String line = null;
int lineCounter = 0;
BufferedReader reader = new BufferedReader(new StringReader(contents));
try {
while ((line = reader.readLine()) != null) {
switch (lineCounter) {
case 0:
if (!"// Generated by the protocol buffer compiler. DO NOT EDIT!".equals(line)) {
return null;
}
lineCounter++;
break;
case 1:
return pathFrom(line);
}
}
} catch (IOException e) {}
return null;
}
private String contentsOf(CEditor cEditor) {
ICElement input = cEditor.getInputCElement();
if (input instanceof ITranslationUnit) {
ITranslationUnit translationUnit = (ITranslationUnit) input;
return new String(translationUnit.getContents());
}
return null;
}
private IPath pathFrom(String line) {
Matcher matcher = PROTO_PATH_PATTERN.matcher(line);
if (!matcher.matches()) {
return null;
}
String path = matcher.group(1);
return (!isEmpty(path)) ? Path.fromOSString(path) : null;
}
}