file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
Task.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/Task.java | package com.tyron.builder.compiler;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.Module;
import java.io.IOException;
/** */
public abstract class Task<T extends Module> {
private final Project mProject;
private final T mModule;
private final ILogger mLogger;
public Task(Project project, T module, ILogger logger) {
mProject = project;
mModule = module;
mLogger = logger;
}
/**
* @return the logger class that this task can use to write logs to
*/
protected ILogger getLogger() {
return mLogger;
}
protected Project getProject() {
return mProject;
}
/**
* @return the Module that this task belongs to
*/
protected T getModule() {
return mModule;
}
/** Called by {@link ApkBuilder} to display the name of the task to the logs */
public abstract String getName();
/**
* Called before run() to give the subclass information about the project
*
* @throws IOException if an exception occurred during a file operation
*/
public abstract void prepare(BuildType type) throws IOException;
/**
* Called by the {@link ApkBuilder} to perform the task needed to do by this subclass
*
* @throws IOException if an exception occurred in a File operation
* @throws CompilationFailedException if an exception occurred while the task is running
*/
public abstract void run() throws IOException, CompilationFailedException;
/** Called after the compilation has finished successfully on every tasks */
protected void clean() {}
}
| 1,660 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
Builder.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/Builder.java | package com.tyron.builder.compiler;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.Module;
import java.io.IOException;
import java.util.List;
public interface Builder<T extends Module> {
interface TaskListener {
@MainThread
void onTaskStarted(String name, String message, int progress);
}
void setTaskListener(TaskListener taskListener);
@NonNull
Project getProject();
T getModule();
void build(BuildType type) throws CompilationFailedException, IOException;
ILogger getLogger();
List<Task<? super T>> getTasks(BuildType type);
}
| 773 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
IncrementalJavaFormatTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/incremental/java/IncrementalJavaFormatTask.java | package com.tyron.builder.compiler.incremental.java;
import com.google.common.base.Throwables;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
public class IncrementalJavaFormatTask extends Task<JavaModule> {
private static final String TAG = "formatJava";
private List<File> mJavaFiles;
public IncrementalJavaFormatTask(Project project, JavaModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
mJavaFiles = new ArrayList<>();
mJavaFiles.addAll(getJavaFiles(new File(getModule().getRootFile() + "/src/main/java")));
}
@Override
public void run() throws IOException, CompilationFailedException {
if (mJavaFiles.isEmpty()) {
return;
}
try {
File buildSettings =
new File(
getModule().getProjectDir(),
".idea/" + getModule().getRootFile().getName() + "_compiler_settings.json");
String content = new String(Files.readAllBytes(Paths.get(buildSettings.getAbsolutePath())));
JSONObject buildSettingsJson = new JSONObject(content);
String applyJavaFormat =
buildSettingsJson.optJSONObject("java").optString("applyJavaFormat", "false");
if (Boolean.parseBoolean(applyJavaFormat)) {
for (File mJava : mJavaFiles) {
StringWriter out = new StringWriter();
StringWriter err = new StringWriter();
String text = new String(Files.readAllBytes(mJava.toPath()));
com.google.googlejavaformat.java.Main main =
new com.google.googlejavaformat.java.Main(
new PrintWriter(out, true),
new PrintWriter(err, true),
new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));
int exitCode = main.format("-");
if (exitCode != 0) {
getLogger().debug("Error: " + mJava.getAbsolutePath() + " " + err.toString());
throw new CompilationFailedException(TAG + " error");
}
String formatted = out.toString();
if (formatted != null && !formatted.isEmpty()) {
FileUtils.writeStringToFile(mJava, formatted, Charset.defaultCharset());
}
}
}
} catch (Exception e) {
throw new CompilationFailedException(Throwables.getStackTraceAsString(e));
}
}
public static Set<File> getJavaFiles(File dir) {
Set<File> javaFiles = new HashSet<>();
File[] files = dir.listFiles();
if (files == null) {
return Collections.emptySet();
}
for (File file : files) {
if (file.isDirectory()) {
javaFiles.addAll(getJavaFiles(file));
} else {
if (file.getName().endsWith(".java")) {
javaFiles.add(file);
}
}
}
return javaFiles;
}
}
| 3,593 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
IncrementalJavaTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/incremental/java/IncrementalJavaTask.java | package com.tyron.builder.compiler.incremental.java;
import android.os.Build;
import android.util.Log;
import androidx.annotation.VisibleForTesting;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;
import com.tyron.builder.BuildModule;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.model.DiagnosticWrapper;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.builder.project.cache.CacheHolder;
import com.tyron.common.util.BinaryExecutor;
import com.tyron.common.util.Cache;
import com.tyron.common.util.ExecutionResult;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.zip.ZipException;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardLocation;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
public class IncrementalJavaTask extends Task<JavaModule> {
public static final CacheHolder.CacheKey<String, List<File>> CACHE_KEY =
new CacheHolder.CacheKey<>("javaCache");
private static final String TAG = "compileJavaWithJavac";
private File mOutputDir;
private List<File> mJavaFiles;
private List<File> mFilesToCompile;
private Cache<String, List<File>> mClassCache;
public IncrementalJavaTask(Project project, JavaModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
mOutputDir = new File(getModule().getBuildDirectory(), "bin/java/classes");
if (!mOutputDir.exists() && !mOutputDir.mkdirs()) {
throw new IOException("Unable to create output directory");
}
mFilesToCompile = new ArrayList<>();
mClassCache = getModule().getCache(CACHE_KEY, new Cache<>());
mJavaFiles = new ArrayList<>();
/*if (getModule() instanceof AndroidModule) {
mJavaFiles.addAll(((AndroidModule) getModule()).getResourceClasses().values());
}*/
mJavaFiles.addAll(getJavaFiles(new File(getModule().getRootFile() + "/src/main/java")));
mJavaFiles.addAll(getJavaFiles(new File(getModule().getBuildDirectory(), "gen")));
mJavaFiles.addAll(getJavaFiles(new File(getModule().getBuildDirectory(), "view_binding")));
for (Cache.Key<String> key : new HashSet<>(mClassCache.getKeys())) {
if (!mJavaFiles.contains(key.file.toFile())) {
File file = mClassCache.get(key.file, "class").iterator().next();
deleteAllFiles(file, ".class");
mClassCache.remove(key.file, "class", "dex");
}
}
for (File file : mJavaFiles) {
Path filePath = file.toPath();
if (mClassCache.needs(filePath, "class")) {
mFilesToCompile.add(file);
}
}
}
private boolean mHasErrors = false;
@Override
public void run() throws IOException, CompilationFailedException {
if (mFilesToCompile.isEmpty()) {
return;
}
try {
File buildSettings =
new File(
getModule().getProjectDir(),
".idea/" + getModule().getRootFile().getName() + "_compiler_settings.json");
String content = new String(Files.readAllBytes(Paths.get(buildSettings.getAbsolutePath())));
JSONObject buildSettingsJson = new JSONObject(content);
boolean isCompilerEnabled =
Boolean.parseBoolean(
buildSettingsJson.optJSONObject("java").optString("isCompilerEnabled", "false"));
String sourceCompatibility =
buildSettingsJson.optJSONObject("java").optString("sourceCompatibility", "1.8");
String targetCompatibility =
buildSettingsJson.optJSONObject("java").optString("targetCompatibility", "1.8");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
BuildModule.getJavac().setReadOnly();
}
if (!isCompilerEnabled) {
Log.d(TAG, "Compiling java files");
DiagnosticListener<JavaFileObject> diagnosticCollector =
diagnostic -> {
switch (diagnostic.getKind()) {
case ERROR:
mHasErrors = true;
getLogger().error(new DiagnosticWrapper(diagnostic));
break;
case WARNING:
getLogger().warning(new DiagnosticWrapper(diagnostic));
}
};
JavacTool tool = JavacTool.create();
JavacFileManager standardJavaFileManager =
tool.getStandardFileManager(
diagnosticCollector, Locale.getDefault(), Charset.defaultCharset());
standardJavaFileManager.setSymbolFileEnabled(false);
File javaDir = new File(getModule().getRootFile() + "/src/main/java");
File buildGenDir = new File(getModule().getRootFile() + "/build/gen");
File viewBindingDir = new File(getModule().getRootFile() + "/build/view_binding");
File api_files = new File(getModule().getRootFile(), "/build/libraries/api_files/libs");
File api_libs = new File(getModule().getRootFile(), "/build/libraries/api_libs");
File kotlinOutputDir = new File(getModule().getBuildDirectory(), "bin/kotlin/classes");
File javaOutputDir = new File(getModule().getBuildDirectory(), "bin/java/classes");
File implementation_files =
new File(getModule().getRootFile(), "/build/libraries/implementation_files/libs");
File implementation_libs =
new File(getModule().getRootFile(), "/build/libraries/implementation_libs");
File runtimeOnly_files =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnly_files/libs");
File runtimeOnly_libs =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnly_libs");
File compileOnly_files =
new File(getModule().getRootFile(), "/build/libraries/compileOnly_files/libs");
File compileOnly_libs =
new File(getModule().getRootFile(), "/build/libraries/compileOnly_libs");
File runtimeOnlyApi_files =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnlyApi_files/libs");
File runtimeOnlyApi_libs =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnlyApi_libs");
File compileOnlyApi_files =
new File(getModule().getRootFile(), "/build/libraries/compileOnlyApi_files/libs");
File compileOnlyApi_libs =
new File(getModule().getRootFile(), "/build/libraries/compileOnlyApi_libs");
List<File> compileClassPath = new ArrayList<>();
compileClassPath.addAll(getJarFiles(api_files));
compileClassPath.addAll(getJarFiles(api_libs));
compileClassPath.addAll(getJarFiles(implementation_files));
compileClassPath.addAll(getJarFiles(implementation_libs));
compileClassPath.addAll(getJarFiles(compileOnly_files));
compileClassPath.addAll(getJarFiles(compileOnly_libs));
compileClassPath.addAll(getJarFiles(compileOnlyApi_files));
compileClassPath.addAll(getJarFiles(compileOnlyApi_libs));
compileClassPath.addAll(getModule().getLibraries());
compileClassPath.add(javaOutputDir);
compileClassPath.add(kotlinOutputDir);
compileClassPath.addAll(getParentJavaFiles(javaDir));
compileClassPath.addAll(getParentJavaFiles(buildGenDir));
compileClassPath.addAll(getParentJavaFiles(viewBindingDir));
compileClassPath.add(BuildModule.getAndroidJar());
compileClassPath.add(BuildModule.getLambdaStubs());
List<File> runtimeClassPath = new ArrayList<>();
runtimeClassPath.addAll(getJarFiles(runtimeOnly_files));
runtimeClassPath.addAll(getJarFiles(runtimeOnly_libs));
runtimeClassPath.addAll(getJarFiles(runtimeOnlyApi_files));
runtimeClassPath.addAll(getJarFiles(runtimeOnlyApi_libs));
runtimeClassPath.addAll(getJarFiles(api_files));
runtimeClassPath.addAll(getJarFiles(api_libs));
runtimeClassPath.addAll(getModule().getLibraries());
runtimeClassPath.add(javaOutputDir);
runtimeClassPath.add(kotlinOutputDir);
runtimeClassPath.addAll(getParentJavaFiles(javaDir));
runtimeClassPath.addAll(getParentJavaFiles(buildGenDir));
runtimeClassPath.addAll(getParentJavaFiles(viewBindingDir));
runtimeClassPath.add(getModule().getBootstrapJarFile());
runtimeClassPath.add(getModule().getLambdaStubsJarFile());
standardJavaFileManager.setLocation(
StandardLocation.CLASS_OUTPUT, Collections.singletonList(mOutputDir));
standardJavaFileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, runtimeClassPath);
standardJavaFileManager.setLocation(StandardLocation.CLASS_PATH, compileClassPath);
standardJavaFileManager.setLocation(StandardLocation.SOURCE_PATH, mJavaFiles);
List<JavaFileObject> javaFileObjects = new ArrayList<>();
for (File file : mFilesToCompile) {
javaFileObjects.add(
new SimpleJavaFileObject(file.toURI(), JavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors)
throws IOException {
return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}
});
}
List<String> options = new ArrayList<>();
options.add("-proc:none");
options.add("-source");
options.add("1.8");
options.add("-target");
options.add("1.8");
options.add("-Xlint:cast");
options.add("-Xlint:deprecation");
options.add("-Xlint:empty");
options.add("-Xlint" + ":fallthrough");
options.add("-Xlint:finally");
options.add("-Xlint:path");
options.add("-Xlint:unchecked");
options.add("-Xlint" + ":varargs");
options.add("-Xlint:static");
JavacTask task =
tool.getTask(
null, standardJavaFileManager, diagnosticCollector, options, null, javaFileObjects);
HashMap<String, List<File>> compiledFiles = new HashMap<>();
task.parse();
task.analyze();
Iterable<? extends JavaFileObject> generate = task.generate();
for (JavaFileObject fileObject : generate) {
String path = fileObject.getName();
File classFile = new File(path);
if (classFile.exists()) {
String classPath =
classFile
.getAbsolutePath()
.replace("build/bin/classes/", "src/main/java/")
.replace(".class", ".java");
if (classFile.getName().indexOf('$') != -1) {
classPath = classPath.substring(0, classPath.indexOf('$')) + ".java";
}
File file = new File(classPath);
if (!file.exists()) {
file = new File(classPath.replace("src/main/java", "build/gen"));
}
if (!compiledFiles.containsKey(file.getAbsolutePath())) {
ArrayList<File> list = new ArrayList<>();
list.add(classFile);
compiledFiles.put(file.getAbsolutePath(), list);
} else {
Objects.requireNonNull(compiledFiles.get(file.getAbsolutePath())).add(classFile);
}
mClassCache.load(file.toPath(), "class", Collections.singletonList(classFile));
}
}
compiledFiles.forEach(
(key, values) -> {
File sourceFile = new File(key);
String name = sourceFile.getName().replace(".java", "");
File first = values.iterator().next();
File parent = first.getParentFile();
if (parent != null) {
File[] children =
parent.listFiles(
c -> {
if (!c.getName().contains("$")) {
return false;
}
String baseClassName = c.getName().substring(0, c.getName().indexOf('$'));
return baseClassName.equals(name);
});
if (children != null) {
for (File file : children) {
if (!values.contains(file)) {
if (file.delete()) {
Log.d(TAG, "Deleted file " + file.getAbsolutePath());
}
}
}
}
}
});
if (mHasErrors) {
throw new CompilationFailedException("Compilation failed, check logs for more details");
}
} else {
File javaDir = new File(getModule().getRootFile() + "/src/main/java");
File buildGenDir = new File(getModule().getRootFile() + "/build/gen");
File viewBindingDir = new File(getModule().getRootFile() + "/build/view_binding");
File api_files = new File(getModule().getRootFile(), "/build/libraries/api_files/libs");
File api_libs = new File(getModule().getRootFile(), "/build/libraries/api_libs");
File kotlinOutputDir = new File(getModule().getBuildDirectory(), "bin/kotlin/classes");
File javaOutputDir = new File(getModule().getBuildDirectory(), "bin/java/classes");
File implementation_files =
new File(getModule().getRootFile(), "/build/libraries/implementation_files/libs");
File implementation_libs =
new File(getModule().getRootFile(), "/build/libraries/implementation_libs");
File runtimeOnly_files =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnly_files/libs");
File runtimeOnly_libs =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnly_libs");
File compileOnly_files =
new File(getModule().getRootFile(), "/build/libraries/compileOnly_files/libs");
File compileOnly_libs =
new File(getModule().getRootFile(), "/build/libraries/compileOnly_libs");
File runtimeOnlyApi_files =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnlyApi_files/libs");
File runtimeOnlyApi_libs =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnlyApi_libs");
File compileOnlyApi_files =
new File(getModule().getRootFile(), "/build/libraries/compileOnlyApi_files/libs");
File compileOnlyApi_libs =
new File(getModule().getRootFile(), "/build/libraries/compileOnlyApi_libs");
List<File> compileClassPath = new ArrayList<>();
compileClassPath.addAll(getJarFiles(api_files));
compileClassPath.addAll(getJarFiles(api_libs));
compileClassPath.addAll(getJarFiles(implementation_files));
compileClassPath.addAll(getJarFiles(implementation_libs));
compileClassPath.addAll(getJarFiles(compileOnly_files));
compileClassPath.addAll(getJarFiles(compileOnly_libs));
compileClassPath.addAll(getJarFiles(compileOnlyApi_files));
compileClassPath.addAll(getJarFiles(compileOnlyApi_libs));
compileClassPath.addAll(getModule().getLibraries());
compileClassPath.add(javaOutputDir);
compileClassPath.add(kotlinOutputDir);
compileClassPath.addAll(getParentJavaFiles(javaDir));
compileClassPath.addAll(getParentJavaFiles(buildGenDir));
compileClassPath.addAll(getParentJavaFiles(viewBindingDir));
compileClassPath.add(BuildModule.getAndroidJar());
compileClassPath.add(BuildModule.getLambdaStubs());
List<File> runtimeClassPath = new ArrayList<>();
runtimeClassPath.addAll(getJarFiles(runtimeOnly_files));
runtimeClassPath.addAll(getJarFiles(runtimeOnly_libs));
runtimeClassPath.addAll(getJarFiles(runtimeOnlyApi_files));
runtimeClassPath.addAll(getJarFiles(runtimeOnlyApi_libs));
runtimeClassPath.addAll(getJarFiles(api_files));
runtimeClassPath.addAll(getJarFiles(api_libs));
runtimeClassPath.addAll(getModule().getLibraries());
runtimeClassPath.add(javaOutputDir);
runtimeClassPath.add(kotlinOutputDir);
runtimeClassPath.addAll(getParentJavaFiles(javaDir));
runtimeClassPath.addAll(getParentJavaFiles(buildGenDir));
runtimeClassPath.addAll(getParentJavaFiles(viewBindingDir));
runtimeClassPath.add(getModule().getBootstrapJarFile());
runtimeClassPath.add(getModule().getLambdaStubsJarFile());
/* String[] command =
new String[] {
"dalvikvm",
"-Xcompiler-option",
"--compiler-filter=speed",
"-Xmx256m",
"-cp",
BuildModule.getJavac().getAbsolutePath(),
"com.sun.tools.javac.MainKt",
"-sourcepath",
mJavaFiles.stream().map(File::toString).collect(Collectors.joining(":")),
"-d",
mOutputDir.getAbsolutePath(),
"-bootclasspath",
runtimeClassPath.stream().map(File::toString).collect(Collectors.joining(":")),
"-classpath",
compileClassPath.stream().map(File::toString).collect(Collectors.joining(":")),
"-source",
sourceCompatibility,
"-target",
targetCompatibility
};
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder output = new StringBuilder(); // To store the output
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n"); // Append each line to the output
}
String message = output.toString();
if (!message.isEmpty()) {
getLogger().info(output.toString());
}
process.waitFor();
if (output.toString().contains("error")) {
throw new CompilationFailedException("Compilation failed, see logs for more details");
}*/
List<String> args = new ArrayList<>();
args.add("dalvikvm");
args.add("-Xcompiler-option");
args.add("--compiler-filter=speed");
args.add("-Xmx256m");
args.add("-cp");
args.add(BuildModule.getJavac().getAbsolutePath());
args.add("com.sun.tools.javac.MainKt");
args.add("-sourcepath");
args.add(mJavaFiles.stream().map(File::toString).collect(Collectors.joining(":")));
args.add("-d");
args.add(mOutputDir.getAbsolutePath());
args.add("-bootclasspath");
args.add(runtimeClassPath.stream().map(File::toString).collect(Collectors.joining(":")));
args.add("-classpath");
args.add(compileClassPath.stream().map(File::toString).collect(Collectors.joining(":")));
args.add("-source");
args.add(sourceCompatibility);
args.add("-target");
args.add(targetCompatibility);
BinaryExecutor executor = new BinaryExecutor();
executor.setCommands(args);
ExecutionResult result = executor.run();
String message = result.getOutput().trim();
if (!message.isEmpty()) {
getLogger().info(message);
}
if (result != null) {
if (result.getExitValue() != 0) {
getLogger().info(executor.getLog().trim());
throw new CompilationFailedException("Compilation failed, see logs for more details");
}
}
}
} catch (Exception e) {
throw new CompilationFailedException(e);
}
}
@VisibleForTesting
public List<File> getCompiledFiles() {
return mFilesToCompile;
}
public static Set<File> getJavaFiles(File dir) {
Set<File> javaFiles = new HashSet<>();
File[] files = dir.listFiles();
if (files == null) {
return Collections.emptySet();
}
for (File file : files) {
if (file.isDirectory()) {
javaFiles.addAll(getJavaFiles(file));
} else {
if (file.getName().endsWith(".java")) {
javaFiles.add(file);
}
}
}
return javaFiles;
}
public static Set<File> getParentJavaFiles(File dir) {
Set<File> javaFiles = new HashSet<>();
File[] files = dir.listFiles();
if (files == null) {
return Collections.emptySet();
}
for (File file : files) {
if (file.isDirectory()) {
javaFiles.addAll(getParentJavaFiles(file));
} else {
if (file.getName().endsWith(".java")) {
javaFiles.add(file.getParentFile());
}
}
}
return javaFiles;
}
public List<File> getJarFiles(File dir) {
List<File> jarFiles = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".jar")) {
// Check if the JarFile is valid before adding it to the list
if (isJarFileValid(file)) {
jarFiles.add(file);
}
} else if (file.isDirectory()) {
// Recursively add JarFiles from subdirectories
jarFiles.addAll(getJarFiles(file));
}
}
}
return jarFiles;
}
public boolean isJarFileValid(File file) {
String message = "File " + file.getParentFile().getName() + " is corrupt! Ignoring.";
try {
// Try to open the JarFile
JarFile jarFile = new JarFile(file);
// If it opens successfully, close it and return true
jarFile.close();
return true;
} catch (ZipException e) {
// If the JarFile is invalid, it will throw a ZipException
getLogger().warning(message);
return false;
} catch (IOException e) {
// If there is some other error reading the JarFile, return false
getLogger().warning(message);
return false;
}
}
private void deleteAllFiles(File classFile, String ext) throws IOException {
File parent = classFile.getParentFile();
String name = classFile.getName().replace(ext, "");
if (parent != null) {
File[] children =
parent.listFiles((c) -> c.getName().endsWith(ext) && c.getName().contains("$"));
if (children != null) {
for (File child : children) {
if (child.getName().startsWith(name)) {
FileUtils.delete(child);
}
}
}
}
if (classFile.exists()) {
FileUtils.delete(classFile);
}
}
}
| 23,415 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
IncrementalKotlinFormatTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/incremental/kotlin/IncrementalKotlinFormatTask.java | package com.tyron.builder.compiler.incremental.kotlin;
import com.google.common.base.Throwables;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
public class IncrementalKotlinFormatTask extends Task<AndroidModule> {
private static final String TAG = "formatKotlin";
private List<File> mKotlinFiles;
public IncrementalKotlinFormatTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
mKotlinFiles = new ArrayList<>();
mKotlinFiles.addAll(getKotlinFiles(new File(getModule().getRootFile() + "/src/main/kotlin")));
mKotlinFiles.addAll(getKotlinFiles(new File(getModule().getRootFile() + "/src/main/java")));
}
@Override
public void run() throws IOException, CompilationFailedException {
if (mKotlinFiles.isEmpty()) {
return;
}
try {
File buildSettings =
new File(
getModule().getProjectDir(),
".idea/" + getModule().getRootFile().getName() + "_compiler_settings.json");
String content = new String(Files.readAllBytes(Paths.get(buildSettings.getAbsolutePath())));
JSONObject buildSettingsJson = new JSONObject(content);
String applyKotlinFormat =
buildSettingsJson.optJSONObject("kotlin").optString("applyKotlinFormat", "false");
if (Boolean.parseBoolean(applyKotlinFormat)) {
for (File mKotlin : mKotlinFiles) {
String text = new String(Files.readAllBytes(mKotlin.toPath()));
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
com.facebook.ktfmt.cli.Main main =
new com.facebook.ktfmt.cli.Main(
new ByteArrayInputStream(text.toString().getBytes(StandardCharsets.UTF_8)),
new PrintStream(out),
new PrintStream(err),
new String[] {"-"});
int exitCode = main.run();
if (exitCode != 0) {
getLogger().debug("Error: " + mKotlin.getAbsolutePath() + " " + err.toString());
throw new CompilationFailedException(TAG + " error");
}
String formatted = out.toString();
if (formatted != null && !formatted.isEmpty()) {
FileUtils.writeStringToFile(mKotlin, formatted, Charset.defaultCharset());
}
}
}
} catch (Exception e) {
throw new CompilationFailedException(Throwables.getStackTraceAsString(e));
}
}
public static Set<File> getKotlinFiles(File dir) {
Set<File> kotlinFiles = new HashSet<>();
File[] files = dir.listFiles();
if (files == null) {
return Collections.emptySet();
}
for (File file : files) {
if (file.isDirectory()) {
kotlinFiles.addAll(getKotlinFiles(file));
} else {
if (file.getName().endsWith(".kt")) {
kotlinFiles.add(file);
}
}
}
return kotlinFiles;
}
}
| 3,807 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
IncrementalKotlinCompiler.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/incremental/kotlin/IncrementalKotlinCompiler.java | package com.tyron.builder.compiler.incremental.kotlin;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.common.base.Throwables;
import com.tyron.builder.BuildModule;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.model.DiagnosticWrapper;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.common.util.BinaryExecutor;
import com.tyron.common.util.ExecutionResult;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.zip.ZipException;
import kotlin.jvm.functions.Function0;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.build.report.ICReporterBase;
import org.jetbrains.kotlin.cli.common.ExitCode;
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation;
import org.jetbrains.kotlin.cli.common.messages.MessageCollector;
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler;
import org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunnerKt;
import org.json.JSONObject;
public class IncrementalKotlinCompiler extends Task<AndroidModule> {
private static final String TAG = "compileKotlin";
private File mKotlinHome;
private File mClassOutput;
private List<File> mFilesToCompile;
private final MessageCollector mCollector = new Collector();
public IncrementalKotlinCompiler(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
mFilesToCompile = new ArrayList<>();
File javaDir = new File(getModule().getRootFile() + "/src/main/java");
File kotlinDir = new File(getModule().getRootFile() + "/src/main/kotlin");
mFilesToCompile.addAll(getSourceFiles(javaDir));
mFilesToCompile.addAll(getSourceFiles(kotlinDir));
// mKotlinHome = new File(BuildModule.getContext().getFilesDir(), "kotlin-home");
// if (!mKotlinHome.exists() && !mKotlinHome.mkdirs()) {
// throw new IOException("Unable to create kotlin home directory");
// }
mClassOutput = new File(getModule().getBuildDirectory(), "bin/kotlin/classes");
if (!mClassOutput.exists() && !mClassOutput.mkdirs()) {
throw new IOException("Unable to create class output directory");
}
}
@Override
public void run() throws IOException, CompilationFailedException {
if (mFilesToCompile.stream().noneMatch(file -> file.getName().endsWith(".kt"))) {
Log.i(TAG, "No kotlin source files, Skipping compilation.");
return;
}
try {
File buildSettings =
new File(
getModule().getProjectDir(),
".idea/" + getModule().getRootFile().getName() + "_compiler_settings.json");
String content = new String(Files.readAllBytes(Paths.get(buildSettings.getAbsolutePath())));
JSONObject buildSettingsJson = new JSONObject(content);
boolean isCompilerEnabled =
Boolean.parseBoolean(
buildSettingsJson.optJSONObject("kotlin").optString("isCompilerEnabled", "false"));
String jvm_target = buildSettingsJson.optJSONObject("kotlin").optString("jvmTarget", "1.8");
// String language_version =
// buildSettingsJson.optJSONObject("kotlin").optString("languageVersion", "2.1");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
BuildModule.getKotlinc().setReadOnly();
}
if (!isCompilerEnabled) {
File api_files = new File(getModule().getRootFile(), "/build/libraries/api_files/libs");
File api_libs = new File(getModule().getRootFile(), "/build/libraries/api_libs");
File kotlinOutputDir = new File(getModule().getBuildDirectory(), "bin/kotlin/classes");
File javaOutputDir = new File(getModule().getBuildDirectory(), "bin/java/classes");
File implementation_files =
new File(getModule().getRootFile(), "/build/libraries/implementation_files/libs");
File implementation_libs =
new File(getModule().getRootFile(), "/build/libraries/implementation_libs");
File runtimeOnly_files =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnly_files/libs");
File runtimeOnly_libs =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnly_libs");
File compileOnly_files =
new File(getModule().getRootFile(), "/build/libraries/compileOnly_files/libs");
File compileOnly_libs =
new File(getModule().getRootFile(), "/build/libraries/compileOnly_libs");
File runtimeOnlyApi_files =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnlyApi_files/libs");
File runtimeOnlyApi_libs =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnlyApi_libs");
File compileOnlyApi_files =
new File(getModule().getRootFile(), "/build/libraries/compileOnlyApi_files/libs");
File compileOnlyApi_libs =
new File(getModule().getRootFile(), "/build/libraries/compileOnlyApi_libs");
List<File> compileClassPath = new ArrayList<>();
compileClassPath.addAll(getJarFiles(api_files));
compileClassPath.addAll(getJarFiles(api_libs));
compileClassPath.addAll(getJarFiles(implementation_files));
compileClassPath.addAll(getJarFiles(implementation_libs));
compileClassPath.addAll(getJarFiles(compileOnly_files));
compileClassPath.addAll(getJarFiles(compileOnly_libs));
compileClassPath.addAll(getJarFiles(compileOnlyApi_files));
compileClassPath.addAll(getJarFiles(compileOnlyApi_libs));
compileClassPath.add(javaOutputDir);
compileClassPath.add(kotlinOutputDir);
List<File> runtimeClassPath = new ArrayList<>();
runtimeClassPath.addAll(getJarFiles(runtimeOnly_files));
runtimeClassPath.addAll(getJarFiles(runtimeOnly_libs));
runtimeClassPath.addAll(getJarFiles(runtimeOnlyApi_files));
runtimeClassPath.addAll(getJarFiles(runtimeOnlyApi_libs));
runtimeClassPath.add(getModule().getBootstrapJarFile());
runtimeClassPath.add(getModule().getLambdaStubsJarFile());
runtimeClassPath.addAll(getJarFiles(api_files));
runtimeClassPath.addAll(getJarFiles(api_libs));
runtimeClassPath.add(javaOutputDir);
runtimeClassPath.add(kotlinOutputDir);
List<File> classpath = new ArrayList<>();
classpath.add(getModule().getBuildClassesDirectory());
classpath.addAll(getModule().getLibraries());
classpath.addAll(compileClassPath);
classpath.addAll(runtimeClassPath);
List<String> arguments = new ArrayList<>();
Collections.addAll(
arguments,
"-cp",
classpath.stream()
.map(File::getAbsolutePath)
.collect(Collectors.joining(File.pathSeparator)));
arguments.add("-Xskip-metadata-version-check");
arguments.add("-Xjvm-default=all");
File javaDir = new File(getModule().getRootFile() + "/src/main/java");
File kotlinDir = new File(getModule().getRootFile() + "/src/main/kotlin");
File buildGenDir = new File(getModule().getRootFile() + "/build/gen");
File viewBindingDir = new File(getModule().getRootFile() + "/build/view_binding");
List<File> javaSourceRoots = new ArrayList<>();
if (javaDir.exists()) {
javaSourceRoots.addAll(getFiles(javaDir, ".java"));
}
if (buildGenDir.exists()) {
javaSourceRoots.addAll(getFiles(buildGenDir, ".java"));
}
if (viewBindingDir.exists()) {
javaSourceRoots.addAll(getFiles(viewBindingDir, ".java"));
}
K2JVMCompiler compiler = new K2JVMCompiler();
K2JVMCompilerArguments args = new K2JVMCompilerArguments();
compiler.parseArguments(arguments.toArray(new String[0]), args);
args.setUseJavac(false);
args.setCompileJava(false);
args.setIncludeRuntime(false);
args.setNoJdk(true);
args.setModuleName(getModule().getRootFile().getName());
args.setNoReflect(true);
args.setNoStdlib(true);
args.setSuppressWarnings(true);
args.setJavaSourceRoots(
javaSourceRoots.stream().map(File::getAbsolutePath).toArray(String[]::new));
// args.setKotlinHome(mKotlinHome.getAbsolutePath());
args.setDestination(mClassOutput.getAbsolutePath());
List<File> plugins = getPlugins();
getLogger().debug("Loading kotlin compiler plugins: " + plugins);
args.setPluginClasspaths(
plugins.stream().map(File::getAbsolutePath).toArray(String[]::new));
args.setPluginOptions(getPluginOptions());
File cacheDir = new File(getModule().getBuildDirectory(), "kotlin/compileKotlin/cacheable");
List<File> fileList = new ArrayList<>();
if (javaDir.exists()) {
fileList.add(javaDir);
}
if (buildGenDir.exists()) {
fileList.add(buildGenDir);
}
if (viewBindingDir.exists()) {
fileList.add(viewBindingDir);
}
if (kotlinDir.exists()) {
fileList.add(kotlinDir);
}
IncrementalJvmCompilerRunnerKt.makeIncrementally(
cacheDir,
Arrays.asList(fileList.toArray(new File[0])),
args,
mCollector,
new ICReporterBase() {
@Override
public void report(@NonNull Function0<String> function0) {
// getLogger().info()
function0.invoke();
}
@Override
public void reportVerbose(@NonNull Function0<String> function0) {
// getLogger().verbose()
function0.invoke();
}
@Override
public void reportCompileIteration(
boolean incremental,
@NonNull Collection<? extends File> sources,
@NonNull ExitCode exitCode) {}
});
if (mCollector.hasErrors()) {
throw new CompilationFailedException("Compilation failed, see logs for more details");
}
} else {
File api_files = new File(getModule().getRootFile(), "/build/libraries/api_files/libs");
File api_libs = new File(getModule().getRootFile(), "/build/libraries/api_libs");
File kotlinOutputDir = new File(getModule().getBuildDirectory(), "bin/kotlin/classes");
File javaOutputDir = new File(getModule().getBuildDirectory(), "bin/java/classes");
File implementation_files =
new File(getModule().getRootFile(), "/build/libraries/implementation_files/libs");
File implementation_libs =
new File(getModule().getRootFile(), "/build/libraries/implementation_libs");
File runtimeOnly_files =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnly_files/libs");
File runtimeOnly_libs =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnly_libs");
File compileOnly_files =
new File(getModule().getRootFile(), "/build/libraries/compileOnly_files/libs");
File compileOnly_libs =
new File(getModule().getRootFile(), "/build/libraries/compileOnly_libs");
File runtimeOnlyApi_files =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnlyApi_files/libs");
File runtimeOnlyApi_libs =
new File(getModule().getRootFile(), "/build/libraries/runtimeOnlyApi_libs");
File compileOnlyApi_files =
new File(getModule().getRootFile(), "/build/libraries/compileOnlyApi_files/libs");
File compileOnlyApi_libs =
new File(getModule().getRootFile(), "/build/libraries/compileOnlyApi_libs");
List<File> compileClassPath = new ArrayList<>();
compileClassPath.addAll(getJarFiles(api_files));
compileClassPath.addAll(getJarFiles(api_libs));
compileClassPath.addAll(getJarFiles(implementation_files));
compileClassPath.addAll(getJarFiles(implementation_libs));
compileClassPath.addAll(getJarFiles(compileOnly_files));
compileClassPath.addAll(getJarFiles(compileOnly_libs));
compileClassPath.addAll(getJarFiles(compileOnlyApi_files));
compileClassPath.addAll(getJarFiles(compileOnlyApi_libs));
compileClassPath.add(javaOutputDir);
compileClassPath.add(kotlinOutputDir);
List<File> runtimeClassPath = new ArrayList<>();
runtimeClassPath.addAll(getJarFiles(runtimeOnly_files));
runtimeClassPath.addAll(getJarFiles(runtimeOnly_libs));
runtimeClassPath.addAll(getJarFiles(runtimeOnlyApi_files));
runtimeClassPath.addAll(getJarFiles(runtimeOnlyApi_libs));
runtimeClassPath.add(getModule().getBootstrapJarFile());
runtimeClassPath.add(getModule().getLambdaStubsJarFile());
runtimeClassPath.addAll(getJarFiles(api_files));
runtimeClassPath.addAll(getJarFiles(api_libs));
runtimeClassPath.add(javaOutputDir);
runtimeClassPath.add(kotlinOutputDir);
List<File> classpath = new ArrayList<>();
classpath.add(getModule().getBuildClassesDirectory());
classpath.addAll(getModule().getLibraries());
classpath.addAll(compileClassPath);
classpath.addAll(runtimeClassPath);
List<String> arguments = new ArrayList<>();
Collections.addAll(
arguments,
classpath.stream()
.map(File::getAbsolutePath)
.collect(Collectors.joining(File.pathSeparator)));
File javaDir = new File(getModule().getRootFile() + "/src/main/java");
File kotlinDir = new File(getModule().getRootFile() + "/src/main/kotlin");
File buildGenDir = new File(getModule().getRootFile() + "/build/gen");
File viewBindingDir = new File(getModule().getRootFile() + "/build/view_binding");
List<File> javaSourceRoots = new ArrayList<>();
if (javaDir.exists()) {
javaSourceRoots.add(javaDir);
}
if (buildGenDir.exists()) {
javaSourceRoots.add(buildGenDir);
}
if (viewBindingDir.exists()) {
javaSourceRoots.add(viewBindingDir);
}
List<File> fileList = new ArrayList<>();
if (javaDir.exists()) {
fileList.add(javaDir);
}
if (buildGenDir.exists()) {
fileList.add(buildGenDir);
}
if (viewBindingDir.exists()) {
fileList.add(viewBindingDir);
}
if (kotlinDir.exists()) {
fileList.add(kotlinDir);
}
List<File> plugins = getPlugins();
getLogger().debug("Loading kotlin compiler plugins: " + plugins);
/* String[] command =
new String[] {
"dalvikvm",
"-Xcompiler-option",
"--compiler-filter=speed",
"-Xmx256m",
"-cp",
compiler_path,
"org.jetbrains.kotlin.cli.jvm.K2JVMCompiler",
"-no-reflect",
"-no-jdk",
"-no-stdlib",
"-jvm-target",
jvm_target,
// "-language-version",
// language_version,
"-cp",
Arrays.toString(arguments.toArray(new String[0])).replace("[", "").replace("]", ""),
"-Xjava-source-roots="
+ Arrays.toString(
javaSourceRoots.stream()
.map(File::getAbsolutePath)
.toArray(String[]::new))
.replace("[", "")
.replace("]", "")
};
for (File file : fileList) {
command = appendElement(command, file.getAbsolutePath());
}
command = appendElement(command, "-d");
command = appendElement(command, mClassOutput.getAbsolutePath());
command = appendElement(command, "-module-name");
command = appendElement(command, getModule().getRootFile().getName());
command = appendElement(command, "-P");
String plugin = "";
String pluginString =
Arrays.toString(plugins.stream().map(File::getAbsolutePath).toArray(String[]::new))
.replace("[", "")
.replace("]", "");
String pluginOptionsString =
Arrays.toString(getPluginOptions()).replace("[", "").replace("]", "");
plugin = pluginString + ":" + (pluginOptionsString.isEmpty() ? ":=" : pluginOptionsString);
command = appendElement(command, "plugin:" + plugin);
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder output = new StringBuilder(); // To store the output
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n"); // Append each line to the output
}
String message = output.toString();
if (!message.isEmpty()) {
getLogger().info(output.toString());
}
process.waitFor();
if (output.toString().contains("error")) {
throw new CompilationFailedException("Compilation failed, see logs for more details");
}*/
List<String> args = new ArrayList<>();
args.add("dalvikvm");
args.add("-Xcompiler-option");
args.add("--compiler-filter=speed");
args.add("-Xmx256m");
args.add("-cp");
args.add(BuildModule.getKotlinc().getAbsolutePath());
args.add("org.jetbrains.kotlin.cli.jvm.K2JVMCompiler");
args.add("-no-jdk");
args.add("-no-stdlib");
args.add("-no-reflect");
args.add("-jvm-target");
args.add(jvm_target);
args.add("-cp");
args.add(String.join(", ", arguments));
args.add(
"-Xjava-source-roots="
+ String.join(
", ",
javaSourceRoots.stream().map(File::getAbsolutePath).toArray(String[]::new)));
for (File file : fileList) {
args.add(file.getAbsolutePath());
}
args.add("-Xjvm-default=all");
args.add("-d");
args.add(mClassOutput.getAbsolutePath());
args.add("-module-name");
args.add(getModule().getRootFile().getName());
String plugin = "";
String pluginString =
Arrays.toString(plugins.stream().map(File::getAbsolutePath).toArray(String[]::new))
.replace("[", "")
.replace("]", "");
String pluginOptionsString =
Arrays.toString(getPluginOptions()).replace("[", "").replace("]", "");
plugin = pluginString + ":" + (pluginOptionsString.isEmpty() ? ":=" : pluginOptionsString);
args.add("-P");
args.add("plugin:" + plugin);
BinaryExecutor executor = new BinaryExecutor();
executor.setCommands(args);
ExecutionResult result = executor.run();
getLogger().info(executor.getLog().trim());
if (result != null) {
if (result.getExitValue() != 0) {
getLogger().info(result.getOutput().trim());
throw new CompilationFailedException("Compilation failed, see logs for more details");
}
}
}
} catch (Exception e) {
throw new CompilationFailedException(Throwables.getStackTraceAsString(e));
}
}
private String[] appendElement(String[] array, String element) {
String[] newArray = new String[array.length + 1];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[array.length] = element;
return newArray;
}
private List<File> getSourceFiles(File dir) {
List<File> files = new ArrayList<>();
File[] children = dir.listFiles();
if (children != null) {
for (File child : children) {
if (child.isDirectory()) {
files.addAll(getSourceFiles(child));
} else {
if (child.getName().endsWith(".kt") || child.getName().endsWith(".java")) {
files.add(child);
}
}
}
}
return files;
}
public static Set<File> getFiles(File dir, String ext) {
Set<File> Files = new HashSet<>();
File[] files = dir.listFiles();
if (files == null) {
return Collections.emptySet();
}
for (File file : files) {
if (file.isDirectory()) {
Files.addAll(getFiles(file, ext));
} else {
if (file.getName().endsWith(ext)) {
Files.add(file);
}
}
}
return Files;
}
private List<File> getPlugins() {
File pluginDir = new File(getModule().getBuildDirectory(), "plugins");
File[] children = pluginDir.listFiles(c -> c.getName().endsWith(".jar"));
if (children == null) {
return Collections.emptyList();
}
return Arrays.stream(children).collect(Collectors.toList());
}
private String[] getPluginOptions() throws IOException {
File pluginDir = new File(getModule().getBuildDirectory(), "plugins");
File args = new File(pluginDir, "args.txt");
if (!args.exists()) {
return new String[0];
}
String string = FileUtils.readFileToString(args, StandardCharsets.UTF_8);
return string.split(" ");
}
private static class Diagnostic extends DiagnosticWrapper {
private final CompilerMessageSeverity mSeverity;
private final String mMessage;
private final CompilerMessageSourceLocation mLocation;
public Diagnostic(
CompilerMessageSeverity severity, String message, CompilerMessageSourceLocation location) {
mSeverity = severity;
mMessage = message;
if (location == null) {
mLocation =
new CompilerMessageSourceLocation() {
@NonNull
@Override
public String getPath() {
return "UNKNOWN";
}
@Override
public int getLine() {
return 0;
}
@Override
public int getColumn() {
return 0;
}
@Override
public int getLineEnd() {
return 0;
}
@Override
public int getColumnEnd() {
return 0;
}
@Override
public String getLineContent() {
return "";
}
};
} else {
mLocation = location;
}
}
@Override
public File getSource() {
if (mLocation == null || TextUtils.isEmpty(mLocation.getPath())) {
return new File("UNKNOWN");
}
return new File(mLocation.getPath());
}
@Override
public Kind getKind() {
switch (mSeverity) {
case ERROR:
return Kind.ERROR;
case STRONG_WARNING:
return Kind.MANDATORY_WARNING;
case WARNING:
return Kind.WARNING;
case LOGGING:
return Kind.OTHER;
default:
case INFO:
return Kind.NOTE;
}
}
@Override
public long getLineNumber() {
return mLocation.getLine();
}
@Override
public long getColumnNumber() {
return mLocation.getColumn();
}
@Override
public String getMessage(Locale locale) {
return mMessage;
}
}
public List<File> getJarFiles(File dir) {
List<File> jarFiles = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".jar")) {
// Check if the JarFile is valid before adding it to the list
if (isJarFileValid(file)) {
jarFiles.add(file);
}
} else if (file.isDirectory()) {
// Recursively add JarFiles from subdirectories
jarFiles.addAll(getJarFiles(file));
}
}
}
return jarFiles;
}
public boolean isJarFileValid(File file) {
String message = "File " + file.getParentFile().getName() + " is corrupt! Ignoring.";
try {
// Try to open the JarFile
JarFile jarFile = new JarFile(file);
// If it opens successfully, close it and return true
jarFile.close();
return true;
} catch (ZipException e) {
// If the JarFile is invalid, it will throw a ZipException
getLogger().warning(message);
return false;
} catch (IOException e) {
// If there is some other error reading the JarFile, return false
getLogger().warning(message);
return false;
}
}
private class Collector implements MessageCollector {
private final List<Diagnostic> mDiagnostics = new ArrayList<>();
private boolean mHasErrors;
@Override
public void clear() {
mDiagnostics.clear();
}
@Override
public boolean hasErrors() {
return mHasErrors;
}
@Override
public void report(
@NotNull CompilerMessageSeverity severity,
@NotNull String message,
CompilerMessageSourceLocation location) {
if (message.contains("No class roots are found in the JDK path")) {
// Android does not have JDK so its okay to ignore this error
return;
}
Diagnostic diagnostic = new Diagnostic(severity, message, location);
mDiagnostics.add(diagnostic);
switch (severity) {
case ERROR:
mHasErrors = true;
getLogger().error(diagnostic);
break;
case STRONG_WARNING:
case WARNING:
getLogger().warning(diagnostic);
break;
case INFO:
getLogger().info(diagnostic);
break;
default:
getLogger().debug(diagnostic);
}
}
}
}
| 26,973 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
IncrementalD8Task.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/incremental/dex/IncrementalD8Task.java | package com.tyron.builder.compiler.incremental.dex;
import android.util.Log;
import com.android.tools.r8.CompilationMode;
import com.android.tools.r8.D8;
import com.android.tools.r8.D8Command;
import com.android.tools.r8.DiagnosticsHandler;
import com.android.tools.r8.OutputMode;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.compiler.dex.D8Task;
import com.tyron.builder.compiler.dex.DexDiagnosticHandler;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.model.Library;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.builder.project.cache.CacheHolder;
import com.tyron.common.util.Cache;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
public class IncrementalD8Task extends Task<AndroidModule> {
private static final String TAG = "mergeDexWithD8";
public static final CacheHolder.CacheKey<String, List<File>> CACHE_KEY =
new CacheHolder.CacheKey<>("dexCache");
private DiagnosticsHandler diagnosticsHandler;
private List<Path> mClassFiles;
private List<Path> mFilesToCompile;
private Cache<String, List<File>> mDexCache;
private Path mOutputPath;
private BuildType mBuildType;
public IncrementalD8Task(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
mBuildType = type;
diagnosticsHandler = new DexDiagnosticHandler(getLogger(), getModule());
mDexCache = getModule().getCache(CACHE_KEY, new Cache<>());
File output = new File(getModule().getBuildDirectory(), "intermediate/classes");
if (!output.exists() && !output.mkdirs()) {
throw new IOException("Unable to create output directory");
}
mOutputPath = output.toPath();
mFilesToCompile = new ArrayList<>();
mClassFiles =
new ArrayList<>(
D8Task.getClassFiles(new File(getModule().getBuildDirectory(), "bin/java/classes")));
mClassFiles.addAll(
D8Task.getClassFiles(new File(getModule().getBuildDirectory(), "bin/kotlin/classes")));
for (Cache.Key<String> key : new HashSet<>(mDexCache.getKeys())) {
if (!mFilesToCompile.contains(key.file)) {
File file = mDexCache.get(key.file, "dex").iterator().next();
deleteAllFiles(file, ".dex");
mDexCache.remove(key.file, "dex");
}
}
for (Path file : mClassFiles) {
if (mDexCache.needs(file, "dex")) {
mFilesToCompile.add(file);
}
}
}
@Override
public void run() throws IOException, CompilationFailedException {
if (mBuildType == BuildType.RELEASE || mBuildType == BuildType.AAB) {
doRelease();
} else if (mBuildType == BuildType.DEBUG) {
doDebug();
}
}
@Override
protected void clean() {
super.clean();
}
private void doRelease() throws CompilationFailedException {
try {
ensureDexedLibraries();
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
D8Command command =
D8Command.builder(diagnosticsHandler)
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.addProgramFiles(mFilesToCompile)
.addLibraryFiles(getLibraryFiles())
.setMinApiLevel(getModule().getMinSdk())
.setMode(CompilationMode.RELEASE)
.setIntermediate(true)
.setOutput(mOutputPath, OutputMode.DexFilePerClassFile)
.build();
D8.run(command);
for (Path file : mFilesToCompile) {
mDexCache.load(file, "dex", Collections.singletonList(getDexFile(file.toFile())));
}
mergeRelease();
} catch (com.android.tools.r8.CompilationFailedException e) {
throw new CompilationFailedException(e);
}
}
private void doDebug() throws CompilationFailedException {
try {
ensureDexedLibraries();
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
D8Command command =
D8Command.builder(diagnosticsHandler)
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.addProgramFiles(mFilesToCompile)
.addLibraryFiles(getLibraryFiles())
.setMinApiLevel(getModule().getMinSdk())
.setMode(CompilationMode.DEBUG)
.setIntermediate(true)
.setOutput(mOutputPath, OutputMode.DexFilePerClassFile)
.build();
D8.run(command);
for (Path file : mFilesToCompile) {
mDexCache.load(file, "dex", Collections.singletonList(getDexFile(file.toFile())));
}
D8Command.Builder builder =
D8Command.builder(diagnosticsHandler)
.addProgramFiles(getAllDexFiles(mOutputPath.toFile()))
.addLibraryFiles(getLibraryFiles())
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.setMinApiLevel(getModule().getMinSdk());
File output = new File(getModule().getBuildDirectory(), "bin");
builder.setMode(CompilationMode.DEBUG);
builder.setOutput(output.toPath(), OutputMode.DexIndexed);
D8.run(builder.build());
} catch (com.android.tools.r8.CompilationFailedException e) {
throw new CompilationFailedException(e);
}
}
private void mergeRelease() throws com.android.tools.r8.CompilationFailedException {
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
File output = new File(getModule().getBuildDirectory(), "bin");
D8Command command =
D8Command.builder(diagnosticsHandler)
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.addLibraryFiles(getLibraryFiles())
.addProgramFiles(getAllDexFiles(mOutputPath.toFile()))
.addProgramFiles(getLibraryDexes())
.setMinApiLevel(getModule().getMinSdk())
.setMode(CompilationMode.RELEASE)
.setOutput(output.toPath(), OutputMode.DexIndexed)
.build();
D8.run(command);
}
private List<Path> getLibraryDexes() {
List<Path> dexes = new ArrayList<>();
for (File file : getModule().getLibraries()) {
File parent = file.getParentFile();
if (parent != null) {
File[] dexFiles = parent.listFiles(file1 -> file1.getName().endsWith(".dex"));
if (dexFiles != null) {
dexes.addAll(Arrays.stream(dexFiles).map(File::toPath).collect(Collectors.toList()));
}
}
}
return dexes;
}
private File getDexFile(File file) {
File output = new File(getModule().getBuildDirectory(), "bin/classes/");
String packageName =
file.getAbsolutePath()
.replace(output.getAbsolutePath(), "")
.substring(1)
.replace(".class", ".dex");
File intermediate = new File(getModule().getBuildDirectory(), "intermediate/classes");
File file1 = new File(intermediate, packageName);
return file1;
}
/**
* Ensures that all libraries of the project has been dex-ed
*
* @throws com.android.tools.r8.CompilationFailedException if the compilation has failed
*/
protected void ensureDexedLibraries() throws com.android.tools.r8.CompilationFailedException {
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
for (File lib : uniqueLibraryFiles) {
File parentFile = lib.getParentFile();
if (parentFile == null) {
continue;
}
File[] libFiles = lib.getParentFile().listFiles();
if (libFiles == null) {
if (!lib.delete()) {
Log.w(TAG, "Failed to delete " + lib.getAbsolutePath());
}
} else {
File dex = new File(lib.getParentFile(), "classes.dex");
if (dex.exists()) {
continue;
}
if (lib.exists()) {
String message;
Library library = getModule().getLibrary(parentFile.getName());
if (library != null) {
boolean declared = library.getDeclaration() != null;
message =
"> DexingWithClasspathTransform "
+ (declared ? library.getDeclaration() : library.getSourceFile().getName());
} else {
message = "> DexingWithClasspathTransform " + parentFile.getName();
}
getLogger().debug(message);
D8Command command =
D8Command.builder(diagnosticsHandler)
.addLibraryFiles(getLibraryFiles())
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.addProgramFiles(lib.toPath())
.setMode(CompilationMode.RELEASE)
.setMinApiLevel(getModule().getMinSdk())
.setOutput(lib.getParentFile().toPath(), OutputMode.DexIndexed)
.build();
D8.run(command);
}
}
}
}
private List<Path> getLibraryFiles() {
List<Path> path = new ArrayList<>();
path.add(getModule().getLambdaStubsJarFile().toPath());
path.add(getModule().getBootstrapJarFile().toPath());
return path;
}
private void deleteAllFiles(File classFile, String ext) throws IOException {
File dexFile = getDexFile(classFile);
if (!dexFile.exists()) {
return;
}
File parent = dexFile.getParentFile();
String name = dexFile.getName().replace(ext, "");
if (parent != null) {
File[] children =
parent.listFiles((c) -> c.getName().endsWith(ext) && c.getName().contains("$"));
if (children != null) {
for (File child : children) {
if (child.getName().startsWith(name)) {
FileUtils.delete(child);
}
}
}
}
FileUtils.delete(dexFile);
}
private List<Path> getAllDexFiles(File dir) {
List<Path> files = new ArrayList<>();
File[] children = dir.listFiles(c -> c.getName().endsWith(".dex") || c.isDirectory());
if (children != null) {
for (File child : children) {
if (child.isDirectory()) {
files.addAll(getAllDexFiles(child));
} else {
files.add(child.toPath());
}
}
}
return files;
}
}
| 12,724 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
IncrementalAssembleLibraryTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/incremental/resource/IncrementalAssembleLibraryTask.java | package com.tyron.builder.compiler.incremental.resource;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import com.android.tools.aapt2.Aapt2Jni;
import com.google.common.base.Throwables;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;
import com.tyron.builder.BuildModule;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.compiler.buildconfig.GenerateDebugBuildConfigTask;
import com.tyron.builder.compiler.buildconfig.GenerateReleaseBuildConfigTask;
import com.tyron.builder.compiler.jar.BuildJarTask;
import com.tyron.builder.compiler.manifest.ManifestMergeTask;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.internal.jar.AssembleJar;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.log.LogUtils;
import com.tyron.builder.model.DiagnosticWrapper;
import com.tyron.builder.model.ModuleSettings;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.builder.project.cache.CacheHolder;
import com.tyron.common.util.BinaryExecutor;
import com.tyron.common.util.Cache;
import com.tyron.common.util.Decompress;
import com.tyron.common.util.ExecutionResult;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardLocation;
import kotlin.jvm.functions.Function0;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.build.report.ICReporterBase;
import org.jetbrains.kotlin.cli.common.ExitCode;
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity;
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation;
import org.jetbrains.kotlin.cli.common.messages.MessageCollector;
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler;
import org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunnerKt;
import org.json.JSONException;
import org.json.JSONObject;
public class IncrementalAssembleLibraryTask extends Task<AndroidModule> {
public static final CacheHolder.CacheKey<String, List<File>> CACHE_KEY =
new CacheHolder.CacheKey<>("javaCache");
private static final String TAG = "assembleLibraries";
private Cache<String, List<File>> mClassCache;
private List<File> subCompileClassPath = new ArrayList<>();
private List<File> subRuntimeClassPath = new ArrayList<>();
private final MessageCollector mCollector = new Collector();
private BuildType mBuildType;
private Set<String> builtProjects = new HashSet<>();
public IncrementalAssembleLibraryTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
mBuildType = type;
}
public void run() throws IOException, CompilationFailedException {
List<String> projects = new ArrayList<>();
projects.addAll(getModule().getAllProjects(getModule().getGradleFile()));
try {
initializeProjects(getModule().getProjectDir(), projects);
} catch (JSONException e) {
}
}
private void initializeProjects(File directory, List<String> rootProjects)
throws IOException, JSONException, CompilationFailedException {
Map<Integer, List<String>> projectsByInclusion = new HashMap<>();
int maxInclusion = 0;
for (String projectName : rootProjects) {
List<String> subProjects =
getModule().getAllProjects(new File(directory, projectName + "/build.gradle"));
int numSubProjects = subProjects.size();
if (numSubProjects == 0) {
projectsByInclusion
.computeIfAbsent(numSubProjects, k -> new ArrayList<>())
.add(projectName);
}
}
for (String projectName : rootProjects) {
List<String> subProjects =
getModule().getAllProjects(new File(directory, projectName + "/build.gradle"));
int numSubProjects = subProjects.size();
if (numSubProjects > 0) {
maxInclusion = Math.max(maxInclusion, numSubProjects);
projectsByInclusion
.computeIfAbsent(numSubProjects, k -> new ArrayList<>())
.add(projectName);
}
}
for (int i = 0; i <= maxInclusion; i++) {
if (projectsByInclusion.containsKey(i)) {
List<String> projects = projectsByInclusion.get(i);
processProjects(directory, projects);
}
}
}
private void processProjects(File projectDir, List<String> projects)
throws IOException, JSONException, CompilationFailedException {
for (String projectName : projects) {
String name = projectName.replaceFirst("/", "").replaceAll("/", ":");
// getLogger().debug("Project: " + name);
Set<String> processedSubProjects = new HashSet<>();
subCompileClassPath.clear();
subRuntimeClassPath.clear();
prepairSubProjects(projectDir, name, processedSubProjects);
}
}
private void prepairSubProjects(File projectDir, String name, Set<String> processedSubProjects)
throws IOException, JSONException, CompilationFailedException {
File gradleFile = new File(projectDir, name + "/build.gradle");
List<String> subProjects = getModule().getAllProjects(gradleFile);
while (!subProjects.isEmpty()) {
String subProject = subProjects.remove(0);
String subName = subProject.replaceFirst("/", "").replaceAll("/", ":");
if (processedSubProjects.contains(subName)) {
// getLogger().debug("Skipping duplicate sub-project: " + subName);
continue;
} else {
processedSubProjects.add(subName);
}
File sub_libraries = new File(projectDir, subName + "/build/libraries");
List<String> sub =
getModule().getAllProjects(new File(projectDir, subName + "/build.gradle"));
for (String projectName : sub) {
String n = projectName.replaceFirst("/", "").replaceAll("/", ":");
File l = new File(projectDir, n + "/build/libraries");
prepairSubProjects(projectDir, n, processedSubProjects);
subCompileClassPath.addAll(getCompileClassPath(l));
subRuntimeClassPath.addAll(getRuntimeClassPath(l));
subCompileClassPath.addAll(addToClassPath(l));
subRuntimeClassPath.addAll(addToClassPath(l));
}
// getLogger().debug("Building sub project: " + subName);
subCompileClassPath.addAll(getCompileClassPath(sub_libraries));
subRuntimeClassPath.addAll(getRuntimeClassPath(sub_libraries));
buildSubProject(projectDir, subName, subCompileClassPath, subRuntimeClassPath);
}
if (!name.isEmpty()) {
if (processedSubProjects.contains(name)) {
// getLogger().debug("Skipping duplicate project: " + name);
return;
}
processedSubProjects.add(name);
File libraries = new File(projectDir, name + "/build/libraries");
// getLogger().debug("Building project: " + name);
subCompileClassPath.addAll(addToClassPath(libraries));
subRuntimeClassPath.addAll(addToClassPath(libraries));
subCompileClassPath.addAll(getCompileClassPath(libraries));
subRuntimeClassPath.addAll(getRuntimeClassPath(libraries));
buildProject(projectDir, name, subCompileClassPath, subRuntimeClassPath);
}
}
private void buildSubProject(
File projectDir, String subName, List<File> compileClassPath, List<File> runtimeClassPath)
throws CompilationFailedException, JSONException, IOException {
File subGradleFile = new File(projectDir, subName + "/build.gradle");
List<String> pluginTypes = new ArrayList<>();
if (builtProjects.contains(subName)) {
// getLogger().debug("Already built project: " + subName);
pluginTypes = getPlugins(subName, subGradleFile);
} else {
pluginTypes = checkPlugins(subName, subGradleFile);
}
if (pluginTypes.isEmpty()) {
getLogger().error("No plugins applied");
throw new CompilationFailedException(
"Unable to find any plugins in "
+ subName
+ "/build.gradle, check project's gradle plugins and build again.");
}
String pluginType = pluginTypes.toString();
compileProject(pluginType, projectDir, subName, compileClassPath, runtimeClassPath);
}
private void buildProject(
File projectDir, String name, List<File> compileClassPath, List<File> runtimeClassPath)
throws CompilationFailedException, JSONException, IOException {
File gradleFile = new File(projectDir, name + "/build.gradle");
List<String> pluginTypes = new ArrayList<>();
if (builtProjects.contains(name)) {
// getLogger().debug("Already built project: " + name);
pluginTypes = getPlugins(name, gradleFile);
} else {
pluginTypes = checkPlugins(name, gradleFile);
}
if (pluginTypes.isEmpty()) {
getLogger().error("No plugins applied");
throw new CompilationFailedException(
"Unable to find any plugins in "
+ name
+ "/build.gradle, check project's gradle plugins and build again.");
}
String pluginType = pluginTypes.toString();
compileProject(pluginType, projectDir, name, compileClassPath, runtimeClassPath);
}
public static boolean hasDirectoryBeenModifiedSinceLastRun(Set<File> files, File config)
throws IOException {
if (files.isEmpty()) {
return false;
}
List<File> fileList = new ArrayList<>(files);
File lastModifiedFile = fileList.get(0);
for (int i = 0; i < fileList.size(); i++) {
if (lastModifiedFile.lastModified() < fileList.get(i).lastModified()) {
lastModifiedFile = fileList.get(i);
}
}
ModuleSettings myModuleSettings = new ModuleSettings(config);
long lastModifiedTime = Long.parseLong(myModuleSettings.getString("lastBuildTime", "0"));
if (lastModifiedTime >= lastModifiedFile.lastModified()) {
return false;
} else {
myModuleSettings
.edit()
.putString("lastBuildTime", String.valueOf(lastModifiedFile.lastModified()))
.apply();
return true;
}
}
private List<String> checkPlugins(String name, File gradleFile) {
List<String> plugins = new ArrayList<>();
List<String> unsupported_plugins = new ArrayList<>();
for (String plugin : getModule().getPlugins(gradleFile)) {
if (plugin.equals("java-library")
|| plugin.equals("com.android.library")
|| plugin.equals("kotlin")
|| plugin.equals("kotlin-android")) {
plugins.add(plugin);
} else {
unsupported_plugins.add(plugin);
}
}
String pluginType = plugins.toString();
getLogger().debug("> Task :" + name + ":" + "checkingPlugins");
if (plugins.isEmpty()) {
} else {
getLogger().debug("NOTE: " + "Plugins applied: " + plugins.toString());
if (unsupported_plugins.isEmpty()) {
} else {
getLogger()
.debug(
"NOTE: "
+ "Unsupported plugins: "
+ unsupported_plugins.toString()
+ " will not be used");
}
}
return plugins;
}
private List<String> getPlugins(String projectName, File gradleFile) {
List<String> plugins = new ArrayList<>();
List<String> unsupported_plugins = new ArrayList<>();
for (String plugin : getModule().getPlugins(gradleFile)) {
if (plugin.equals("java-library")
|| plugin.equals("com.android.library")
|| plugin.equals("kotlin")
|| plugin.equals("kotlin-android")) {
plugins.add(plugin);
} else {
unsupported_plugins.add(plugin);
}
}
return plugins;
}
public void compileProject(
String pluginType,
File projectDir,
String projectName,
List<File> compileClassPath,
List<File> runtimeClassPath)
throws IOException, JSONException, CompilationFailedException {
File gradleFile = new File(projectDir, projectName + "/build.gradle");
File jarDir = new File(projectDir, projectName + "/build/outputs/jar");
File jarFileDir = new File(jarDir, projectName + ".jar");
File root = new File(projectDir, projectName);
File javaDir = new File(projectDir, projectName + "/src/main/java");
File kotlinDir = new File(projectDir, projectName + "/src/main/kotlin");
File javaClassesDir = new File(projectDir, projectName + "/build/classes/java/main");
File kotlinClassesDir = new File(projectDir, projectName + "/build/classes/kotlin/main");
File transformsDir =
new File(projectDir, projectName + "/build/.transforms/transformed/" + projectName);
File transformedJarFileDir = new File(transformsDir, projectName + ".jar");
File classesJarFileDir = new File(transformsDir, "classes.jar");
File resDir = new File(projectDir, projectName + "/src/main/res");
File binResDir = new File(projectDir, projectName + "/build/bin/res");
File buildDir = new File(projectDir, projectName + "/build");
File buildGenDir = new File(projectDir, projectName + "/build/gen");
File viewBindingDir = new File(projectDir, projectName + "/build/view_binding");
File manifestBinFileDir = new File(projectDir, projectName + "/build/bin/AndroidManifest.xml");
File manifestFileDir = new File(projectDir, projectName + "/src/main/AndroidManifest.xml");
File assetsDir = new File(projectDir, projectName + "/src/main/assets");
File aarDir = new File(projectDir, projectName + "/build/bin/aar");
File outputsDir = new File(projectDir, projectName + "/build/outputs/aar");
File aarFileDir = new File(outputsDir, projectName + ".aar");
File config = new File(jarDir, "last-build.bin");
Set<File> javaFiles = new HashSet<>();
Set<File> kotlinFiles = new HashSet<>();
File buildSettings =
new File(getModule().getProjectDir(), ".idea/" + projectName + "_compiler_settings.json");
String content = new String(Files.readAllBytes(Paths.get(buildSettings.getAbsolutePath())));
JSONObject buildSettingsJson = new JSONObject(content);
boolean isSkipKotlinTask =
Optional.ofNullable(buildSettingsJson.optJSONObject("kotlin"))
.map(json -> json.optString("skipKotlinTask", "false"))
.map(Boolean::parseBoolean)
.orElse(false);
boolean isSkipJavaTask =
Optional.ofNullable(buildSettingsJson.optJSONObject("java"))
.map(json -> json.optString("skipJavaTask", "false"))
.map(Boolean::parseBoolean)
.orElse(false);
if (pluginType.equals("[java-library]")) {
if (builtProjects.contains(projectName)) {
// getLogger().debug("Already built project: " + projectName);
subCompileClassPath.add(new File(transformsDir, "classes.jar"));
subRuntimeClassPath.add(new File(transformsDir, "classes.jar"));
getModule().addLibrary(new File(transformsDir, "classes.jar"));
return;
}
javaFiles.addAll(getFiles(javaDir, ".java"));
javaFiles.addAll(getFiles(buildGenDir, ".java"));
if (!jarFileDir.exists() || hasDirectoryBeenModifiedSinceLastRun(javaFiles, config)) {
// If the JAR file directory doesn't exist or the Java files have been modified,
// compile the Java files, create a JAR file, and add the JAR file to the classpaths.
compileClassPath.add(javaClassesDir);
runtimeClassPath.add(javaClassesDir);
compileJava(javaFiles, javaClassesDir, projectName, compileClassPath, runtimeClassPath);
if (isSkipJavaTask) {
getLogger().debug("> Task :" + projectName + ":" + "jar SKIPPED");
} else {
BuildJarTask buildJarTask = new BuildJarTask(getProject(), getModule(), getLogger());
buildJarTask.assembleJar(javaClassesDir, jarFileDir);
getLogger().debug("> Task :" + projectName + ":" + "jar");
copyResources(jarFileDir, transformsDir.getAbsolutePath());
if (!transformedJarFileDir.renameTo(classesJarFileDir)) {
getLogger().warning("Failed to rename " + transformedJarFileDir.getName() + " file");
}
}
} else {
getLogger().debug("> Task :" + projectName + ":" + "jar SKIPPED");
}
builtProjects.add(projectName);
subCompileClassPath.add(new File(transformsDir, "classes.jar"));
subRuntimeClassPath.add(new File(transformsDir, "classes.jar"));
getModule().addLibrary(new File(transformsDir, "classes.jar"));
} else if (pluginType.equals("[java-library, kotlin]")
|| pluginType.equals("[kotlin, java-library]")) {
if (builtProjects.contains(projectName)) {
// getLogger().debug("Already built project: " + projectName);
subCompileClassPath.add(new File(transformsDir, "classes.jar"));
subRuntimeClassPath.add(new File(transformsDir, "classes.jar"));
getModule().addLibrary(new File(transformsDir, "classes.jar"));
return;
}
kotlinFiles.addAll(getFiles(kotlinDir, ".kt"));
kotlinFiles.addAll(getFiles(javaDir, ".kt"));
javaFiles.addAll(getFiles(javaDir, ".java"));
javaFiles.addAll(getFiles(buildGenDir, ".java"));
List<File> sourceFolders = new ArrayList<>();
sourceFolders.add(new File(projectDir, projectName + "/build/classes/java/main"));
sourceFolders.add(new File(projectDir, projectName + "/build/classes/kotlin/main"));
if (!jarFileDir.exists()
|| hasDirectoryBeenModifiedSinceLastRun(kotlinFiles, config)
|| hasDirectoryBeenModifiedSinceLastRun(javaFiles, config)) {
// If the JAR file directory doesn't exist or the Java files have been modified,
// compile the Java files, create a JAR file, and add the JAR file to the classpaths.
compileKotlin(
kotlinFiles, kotlinClassesDir, projectName, compileClassPath, runtimeClassPath);
compileClassPath.add(javaClassesDir);
runtimeClassPath.add(javaClassesDir);
compileClassPath.add(kotlinClassesDir);
runtimeClassPath.add(kotlinClassesDir);
compileJava(javaFiles, javaClassesDir, projectName, compileClassPath, runtimeClassPath);
if (isSkipKotlinTask && isSkipJavaTask) {
getLogger().debug("> Task :" + projectName + ":" + "jar SKIPPED");
} else {
BuildJarTask buildJarTask = new BuildJarTask(getProject(), getModule(), getLogger());
buildJarTask.assembleJar(sourceFolders, jarFileDir);
getLogger().debug("> Task :" + projectName + ":" + "jar");
copyResources(jarFileDir, transformsDir.getAbsolutePath());
if (!transformedJarFileDir.renameTo(classesJarFileDir)) {
getLogger().warning("Failed to rename " + transformedJarFileDir.getName() + " file");
}
}
} else {
getLogger().debug("> Task :" + projectName + ":" + "jar SKIPPED");
}
builtProjects.add(projectName);
subCompileClassPath.add(new File(transformsDir, "classes.jar"));
subRuntimeClassPath.add(new File(transformsDir, "classes.jar"));
getModule().addLibrary(new File(transformsDir, "classes.jar"));
} else if (pluginType.equals("[com.android.library]")) {
if (builtProjects.contains(projectName)) {
// getLogger().debug("Already built project: " + projectName);
subCompileClassPath.add(new File(transformsDir, "classes.jar"));
subRuntimeClassPath.add(new File(transformsDir, "classes.jar"));
getModule().addLibrary(new File(transformsDir, "classes.jar"));
return;
}
javaFiles.addAll(getFiles(javaDir, ".java"));
if (manifestFileDir.exists()) {
if (mBuildType == BuildType.RELEASE || mBuildType == BuildType.AAB) {
getLogger().debug("> Task :" + projectName + ":" + "generateReleaseBuildConfig");
GenerateReleaseBuildConfigTask generateReleaseBuildConfigTask =
new GenerateReleaseBuildConfigTask(getProject(), getModule(), getLogger());
generateReleaseBuildConfigTask.GenerateBuildConfig(
getModule().getNameSpace(gradleFile), buildGenDir);
} else if (mBuildType == BuildType.DEBUG) {
getLogger().debug("> Task :" + projectName + ":" + "generateDebugBuildConfig");
GenerateDebugBuildConfigTask generateDebugBuildConfigTask =
new GenerateDebugBuildConfigTask(getProject(), getModule(), getLogger());
generateDebugBuildConfigTask.GenerateBuildConfig(
getModule().getNameSpace(gradleFile), buildGenDir);
}
ManifestMergeTask manifestMergeTask =
new ManifestMergeTask(getProject(), getModule(), getLogger());
manifestMergeTask.merge(root, gradleFile);
if (resDir.exists()) {
if (javaClassesDir.exists()) {
FileUtils.deleteDirectory(javaClassesDir);
}
if (aarDir.exists()) {
FileUtils.deleteDirectory(aarDir);
}
List<File> librariesToCompile = getLibraries(projectName, binResDir);
compileRes(resDir, binResDir, projectName);
compileLibraries(librariesToCompile, projectName, binResDir);
linkRes(binResDir, projectName, manifestBinFileDir, assetsDir);
}
javaFiles.addAll(getFiles(buildGenDir, ".java"));
javaFiles.addAll(getFiles(viewBindingDir, ".java"));
compileClassPath.add(javaClassesDir);
runtimeClassPath.add(javaClassesDir);
compileJava(javaFiles, javaClassesDir, projectName, compileClassPath, runtimeClassPath);
if (isSkipJavaTask) {
getLogger().debug("> Task :" + projectName + ":" + "aar SKIPPED");
} else {
getLogger().debug("> Task :" + projectName + ":" + "aar");
assembleAar(javaClassesDir, aarDir, buildDir, projectName);
Decompress.unzip(aarFileDir.getAbsolutePath(), transformsDir.getAbsolutePath());
}
} else {
throw new CompilationFailedException("Manifest file does not exist.");
}
builtProjects.add(projectName);
subCompileClassPath.add(new File(transformsDir, "classes.jar"));
subRuntimeClassPath.add(new File(transformsDir, "classes.jar"));
getModule().addLibrary(new File(transformsDir, "classes.jar"));
} else if (pluginType.equals("[com.android.library, kotlin]")
|| pluginType.equals("[kotlin, com.android.library]")
|| pluginType.equals("[com.android.library, kotlin-android]")
|| pluginType.equals("[kotlin-android, com.android.library]")) {
if (builtProjects.contains(projectName)) {
// getLogger().debug("Already built project: " + projectName);
subCompileClassPath.add(new File(transformsDir, "classes.jar"));
subRuntimeClassPath.add(new File(transformsDir, "classes.jar"));
getModule().addLibrary(new File(transformsDir, "classes.jar"));
return;
}
kotlinFiles.addAll(getFiles(kotlinDir, ".kt"));
kotlinFiles.addAll(getFiles(javaDir, ".kt"));
javaFiles.addAll(getFiles(javaDir, ".java"));
List<File> sourceFolders = new ArrayList<>();
sourceFolders.add(new File(projectDir, projectName + "/build/classes/java/main"));
sourceFolders.add(new File(projectDir, projectName + "/build/classes/kotlin/main"));
if (manifestFileDir.exists()) {
if (mBuildType == BuildType.RELEASE || mBuildType == BuildType.AAB) {
getLogger().debug("> Task :" + projectName + ":" + "generateReleaseBuildConfig");
GenerateReleaseBuildConfigTask generateReleaseBuildConfigTask =
new GenerateReleaseBuildConfigTask(getProject(), getModule(), getLogger());
generateReleaseBuildConfigTask.GenerateBuildConfig(
getModule().getNameSpace(gradleFile), buildGenDir);
} else if (mBuildType == BuildType.DEBUG) {
getLogger().debug("> Task :" + projectName + ":" + "generateDebugBuildConfig");
GenerateDebugBuildConfigTask generateDebugBuildConfigTask =
new GenerateDebugBuildConfigTask(getProject(), getModule(), getLogger());
generateDebugBuildConfigTask.GenerateBuildConfig(
getModule().getNameSpace(gradleFile), buildGenDir);
}
ManifestMergeTask manifestMergeTask =
new ManifestMergeTask(getProject(), getModule(), getLogger());
manifestMergeTask.merge(root, gradleFile);
if (resDir.exists()) {
if (javaClassesDir.exists()) {
FileUtils.deleteDirectory(javaClassesDir);
}
if (aarDir.exists()) {
FileUtils.deleteDirectory(aarDir);
}
List<File> librariesToCompile = getLibraries(projectName, binResDir);
compileRes(resDir, binResDir, projectName);
compileLibraries(librariesToCompile, projectName, binResDir);
linkRes(binResDir, projectName, manifestBinFileDir, assetsDir);
}
javaFiles.addAll(getFiles(buildGenDir, ".java"));
javaFiles.addAll(getFiles(viewBindingDir, ".java"));
compileKotlin(
kotlinFiles, kotlinClassesDir, projectName, compileClassPath, runtimeClassPath);
compileClassPath.add(javaClassesDir);
runtimeClassPath.add(javaClassesDir);
compileClassPath.add(kotlinClassesDir);
runtimeClassPath.add(kotlinClassesDir);
compileJava(javaFiles, javaClassesDir, projectName, compileClassPath, runtimeClassPath);
if (isSkipKotlinTask && isSkipJavaTask) {
getLogger().debug("> Task :" + projectName + ":" + "aar SKIPPED");
} else {
getLogger().debug("> Task :" + projectName + ":" + "aar");
assembleAar(sourceFolders, aarDir, buildDir, projectName);
Decompress.unzip(aarFileDir.getAbsolutePath(), transformsDir.getAbsolutePath());
}
} else {
throw new CompilationFailedException("Manifest file does not exist.");
}
builtProjects.add(projectName);
subCompileClassPath.add(new File(transformsDir, "classes.jar"));
subRuntimeClassPath.add(new File(transformsDir, "classes.jar"));
getModule().addLibrary(new File(transformsDir, "classes.jar"));
}
}
private List<File> getCompileClassPath(File libraries) {
List<File> compileClassPath = new ArrayList<>();
compileClassPath.addAll(getJarFiles(new File(libraries, "api_files/libs")));
compileClassPath.addAll(getJarFiles(new File(libraries, "api_libs")));
compileClassPath.addAll(getJarFiles(new File(libraries, "implementation_files/libs")));
compileClassPath.addAll(getJarFiles(new File(libraries, "implementation_libs")));
compileClassPath.addAll(getJarFiles(new File(libraries, "compileOnly_files/libs")));
compileClassPath.addAll(getJarFiles(new File(libraries, "compileOnly_libs")));
compileClassPath.addAll(getJarFiles(new File(libraries, "compileOnlyApi_files/libs")));
compileClassPath.addAll(getJarFiles(new File(libraries, "compileOnlyApi_libs")));
return compileClassPath;
}
private List<File> addToClassPath(File libraries) {
List<File> classPath = new ArrayList<>();
classPath.addAll(getJarFiles(new File(libraries, "api_files/libs")));
classPath.addAll(getJarFiles(new File(libraries, "api_libs")));
for (File jar : classPath) {
getModule().addLibrary(jar);
}
return classPath;
}
private List<File> getRuntimeClassPath(File libraries) {
List<File> runtimeClassPath = new ArrayList<>();
runtimeClassPath.addAll(getJarFiles(new File(libraries, "runtimeOnly_files/libs")));
runtimeClassPath.addAll(getJarFiles(new File(libraries, "runtimeOnly_libs")));
runtimeClassPath.addAll(getJarFiles(new File(libraries, "api_files/libs")));
runtimeClassPath.addAll(getJarFiles(new File(libraries, "api_libs")));
runtimeClassPath.addAll(getJarFiles(new File(libraries, "implementation_files/libs")));
runtimeClassPath.addAll(getJarFiles(new File(libraries, "implementation_libs")));
runtimeClassPath.addAll(getJarFiles(new File(libraries, "runtimeOnlyApi_files/libs")));
runtimeClassPath.addAll(getJarFiles(new File(libraries, "runtimeOnlyApi_libs")));
return runtimeClassPath;
}
private List<File> getLibraries(String root, File bin_res) throws IOException {
if (!bin_res.exists()) {
if (!bin_res.mkdirs()) {
throw new IOException("Failed to create resource directory");
}
}
List<File> libraries = new ArrayList<>();
for (File library :
getLibraries(
new File(getModule().getProjectDir(), root + "/build/libraries/api_files/libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(new File(getModule().getProjectDir(), root + "/build/libraries/api_libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(
new File(
getModule().getProjectDir(),
root + "/build/libraries/implementation_files/libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(
new File(getModule().getProjectDir(), root + "/build/libraries/implementation_libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(
new File(
getModule().getProjectDir(), root + "/build/libraries/compileOnly_files/libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(
new File(
getModule().getProjectDir(),
root + "/build/libraries/compileOnlyApi_files/libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(
new File(getModule().getProjectDir(), root + "/build/libraries/compileOnly_libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(
new File(getModule().getProjectDir(), root + "/build/libraries/compileOnlyApi_libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(
new File(
getModule().getProjectDir(), root + "/build/libraries/runtimeOnly_files/libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(
new File(
getModule().getProjectDir(),
root + "/build/libraries/runtimeOnlyApi_files/libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(
new File(getModule().getProjectDir(), root + "/build/libraries/runtimeOnly_libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
for (File library :
getLibraries(
new File(getModule().getProjectDir(), root + "/build/libraries/runtimeOnlyApi_libs"))) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(bin_res, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
return libraries;
}
private List<File> getLibraries(File dir) {
List<File> libraries = new ArrayList<>();
File[] libs = dir.listFiles(File::isDirectory);
if (libs != null) {
for (File directory : libs) {
File check = new File(directory, "classes.jar");
if (check.exists()) {
libraries.add(check);
}
}
}
return libraries;
}
private void compileLibraries(List<File> libraries, String root, File bin_res)
throws IOException, CompilationFailedException {
Log.d(TAG, "Compiling libraries.");
if (!bin_res.exists()) {
if (!bin_res.mkdirs()) {
throw new IOException("Failed to create resource output directory");
}
}
for (File file : libraries) {
File parent = file.getParentFile();
if (parent == null) {
throw new IOException("Library folder doesn't exist");
}
File[] files = parent.listFiles();
if (files == null) {
continue;
}
for (File inside : files) {
if (inside.isDirectory() && inside.getName().equals("res")) {
List<String> args = new ArrayList<>();
args.add("--dir");
args.add(inside.getAbsolutePath());
args.add("-o");
args.add(createNewFile(bin_res, parent.getName() + ".zip").getAbsolutePath());
int compile = Aapt2Jni.compile(args);
List<DiagnosticWrapper> logs = Aapt2Jni.getLogs();
LogUtils.log(logs, getLogger());
if (compile != 0) {
throw new CompilationFailedException(
"Compilation failed, check logs for more details.");
}
}
}
}
}
private void assembleAar(List<File> inputFolders, File aar, File build, String name)
throws IOException, CompilationFailedException {
if (!aar.exists()) {
if (!aar.mkdirs()) {
throw new IOException("Failed to create resource aar directory");
}
}
AssembleJar assembleJar = new AssembleJar(false);
assembleJar.setOutputFile(new File(aar.getAbsolutePath(), "classes.jar"));
assembleJar.createJarArchive(inputFolders);
File library = new File(getModule().getProjectDir(), name + "/build/outputs/aar/");
if (!library.exists()) {
if (!library.mkdirs()) {
throw new IOException("Failed to create resource libs directory");
}
}
File res = new File(getModule().getProjectDir(), name + "/src/main/res");
copyResources(
new File(getModule().getProjectDir(), name + "/src/main/AndroidManifest.xml"),
aar.getAbsolutePath());
if (res.exists()) {
copyResources(res, aar.getAbsolutePath());
}
File assets = new File(getModule().getProjectDir(), name + "/src/main/assets");
File jniLibs = new File(getModule().getProjectDir(), name + "/src/main/jniLibs");
if (assets.exists()) {
copyResources(assets, aar.getAbsolutePath());
}
if (jniLibs.exists()) {
copyResources(jniLibs, aar.getAbsolutePath());
File jni = new File(aar.getAbsolutePath(), "jniLibs");
jni.renameTo(new File(aar.getAbsolutePath(), "jni"));
}
zipFolder(
Paths.get(aar.getAbsolutePath()), Paths.get(library.getAbsolutePath(), name + ".aar"));
if (aar.exists()) {
FileUtils.deleteDirectory(aar);
}
}
private void assembleAar(File input, File aar, File build, String name)
throws IOException, CompilationFailedException {
if (!aar.exists()) {
if (!aar.mkdirs()) {
throw new IOException("Failed to create resource aar directory");
}
}
AssembleJar assembleJar = new AssembleJar(false);
assembleJar.setOutputFile(new File(aar.getAbsolutePath(), "classes.jar"));
assembleJar.createJarArchive(input);
File library = new File(getModule().getProjectDir(), name + "/build/outputs/aar/");
if (!library.exists()) {
if (!library.mkdirs()) {
throw new IOException("Failed to create resource libs directory");
}
}
File res = new File(getModule().getProjectDir(), name + "/src/main/res");
copyResources(
new File(getModule().getProjectDir(), name + "/src/main/AndroidManifest.xml"),
aar.getAbsolutePath());
if (res.exists()) {
copyResources(res, aar.getAbsolutePath());
}
File assets = new File(getModule().getProjectDir(), name + "/src/main/assets");
File jniLibs = new File(getModule().getProjectDir(), name + "/src/main/jniLibs");
if (assets.exists()) {
copyResources(assets, aar.getAbsolutePath());
}
if (jniLibs.exists()) {
copyResources(jniLibs, aar.getAbsolutePath());
File jni = new File(aar.getAbsolutePath(), "jniLibs");
jni.renameTo(new File(aar.getAbsolutePath(), "jni"));
}
zipFolder(
Paths.get(aar.getAbsolutePath()), Paths.get(library.getAbsolutePath(), name + ".aar"));
if (aar.exists()) {
FileUtils.deleteDirectory(aar);
}
}
public void compileKotlin(
Set<File> kotlinFiles,
File out,
String name,
List<File> compileClassPath,
List<File> runtimeClassPath)
throws IOException, CompilationFailedException {
if (!out.exists()) {
if (!out.mkdirs()) {
throw new IOException("Failed to create resource output directory");
}
}
try {
File buildSettings =
new File(getModule().getProjectDir(), ".idea/" + name + "_compiler_settings.json");
String content = new String(Files.readAllBytes(Paths.get(buildSettings.getAbsolutePath())));
JSONObject buildSettingsJson = new JSONObject(content);
boolean isCompilerEnabled =
Boolean.parseBoolean(
buildSettingsJson.optJSONObject("kotlin").optString("isCompilerEnabled", "false"));
boolean isSkipKotlinTask =
Boolean.parseBoolean(
buildSettingsJson.optJSONObject("kotlin").optString("skipKotlinTask", "false"));
String jvm_target = buildSettingsJson.optJSONObject("kotlin").optString("jvmTarget", "1.8");
// String language_version =
// buildSettingsJson.optJSONObject("kotlin").optString("languageVersion", "2.1");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
BuildModule.getKotlinc().setReadOnly();
}
if (isSkipKotlinTask) {
getLogger().debug("> Task :" + name + ":" + "compileKotlin SKIPPED");
return;
}
if (!isCompilerEnabled) {
List<File> mFilesToCompile = new ArrayList<>();
mClassCache = getModule().getCache(CACHE_KEY, new Cache<>());
for (Cache.Key<String> key : new HashSet<>(mClassCache.getKeys())) {
if (!mFilesToCompile.contains(key.file.toFile())) {
File file = mClassCache.get(key.file, "class").iterator().next();
deleteAllFiles(file, ".class");
mClassCache.remove(key.file, "class", "dex");
}
}
mFilesToCompile.addAll(kotlinFiles);
if (mFilesToCompile.isEmpty()) {
getLogger().debug("> Task :" + name + ":" + "compileKotlin SKIPPED");
return;
} else {
getLogger().debug("> Task :" + name + ":" + "compileKotlin");
}
List<File> classpath = new ArrayList<>();
classpath.add(getModule().getBootstrapJarFile());
classpath.add(getModule().getLambdaStubsJarFile());
classpath.addAll(compileClassPath);
classpath.addAll(runtimeClassPath);
List<String> arguments = new ArrayList<>();
Collections.addAll(
arguments,
"-cp",
classpath.stream()
.map(File::getAbsolutePath)
.collect(Collectors.joining(File.pathSeparator)));
arguments.add("-Xskip-metadata-version-check");
File javaDir = new File(getModule().getProjectDir(), name + "/src/main/java");
File kotlinDir = new File(getModule().getProjectDir(), name + "/src/main/kotlin");
File buildGenDir = new File(getModule().getProjectDir(), name + "/build/gen");
File viewBindingDir = new File(getModule().getProjectDir(), name + "/build/view_binding");
List<File> javaSourceRoots = new ArrayList<>();
if (javaDir.exists()) {
javaSourceRoots.addAll(getFiles(javaDir, ".java"));
}
if (buildGenDir.exists()) {
javaSourceRoots.addAll(getFiles(buildGenDir, ".java"));
}
if (viewBindingDir.exists()) {
javaSourceRoots.addAll(getFiles(viewBindingDir, ".java"));
}
K2JVMCompiler compiler = new K2JVMCompiler();
K2JVMCompilerArguments args = new K2JVMCompilerArguments();
compiler.parseArguments(arguments.toArray(new String[0]), args);
args.setUseJavac(false);
args.setCompileJava(false);
args.setIncludeRuntime(false);
args.setNoJdk(true);
args.setModuleName(name);
args.setNoReflect(true);
args.setNoStdlib(true);
args.setSuppressWarnings(true);
args.setJavaSourceRoots(
javaSourceRoots.stream().map(File::getAbsolutePath).toArray(String[]::new));
// args.setKotlinHome(mKotlinHome.getAbsolutePath());
args.setDestination(out.getAbsolutePath());
List<File> plugins = getPlugins();
getLogger().debug("Loading kotlin compiler plugins: " + plugins);
args.setPluginClasspaths(
plugins.stream().map(File::getAbsolutePath).toArray(String[]::new));
args.setPluginOptions(getPluginOptions());
File cacheDir =
new File(getModule().getProjectDir(), name + "/build/kotlin/compileKotlin/cacheable");
List<File> fileList = new ArrayList<>();
if (javaDir.exists()) {
fileList.add(javaDir);
}
if (buildGenDir.exists()) {
fileList.add(buildGenDir);
}
if (viewBindingDir.exists()) {
fileList.add(viewBindingDir);
}
if (kotlinDir.exists()) {
fileList.add(kotlinDir);
}
IncrementalJvmCompilerRunnerKt.makeIncrementally(
cacheDir,
Arrays.asList(fileList.toArray(new File[0])),
args,
mCollector,
new ICReporterBase() {
@Override
public void report(@NonNull Function0<String> function0) {
// getLogger().info()
function0.invoke();
}
@Override
public void reportVerbose(@NonNull Function0<String> function0) {
// getLogger().verbose()
function0.invoke();
}
@Override
public void reportCompileIteration(
boolean incremental,
@NonNull Collection<? extends File> sources,
@NonNull ExitCode exitCode) {}
});
if (mCollector.hasErrors()) {
throw new CompilationFailedException("Compilation failed, see logs for more details");
} else {
getLogger().debug("> Task :" + name + ":" + "classes");
}
} else {
List<File> mFilesToCompile = new ArrayList<>();
mClassCache = getModule().getCache(CACHE_KEY, new Cache<>());
for (Cache.Key<String> key : new HashSet<>(mClassCache.getKeys())) {
if (!mFilesToCompile.contains(key.file.toFile())) {
File file = mClassCache.get(key.file, "class").iterator().next();
deleteAllFiles(file, ".class");
mClassCache.remove(key.file, "class", "dex");
}
}
mFilesToCompile.addAll(kotlinFiles);
if (mFilesToCompile.isEmpty()) {
getLogger().debug("> Task :" + name + ":" + "compileKotlin SKIPPED");
return;
} else {
getLogger().debug("> Task :" + name + ":" + "compileKotlin");
}
List<File> classpath = new ArrayList<>();
classpath.add(getModule().getBootstrapJarFile());
classpath.add(getModule().getLambdaStubsJarFile());
classpath.addAll(compileClassPath);
classpath.addAll(runtimeClassPath);
List<String> arguments = new ArrayList<>();
Collections.addAll(
arguments,
classpath.stream()
.map(File::getAbsolutePath)
.collect(Collectors.joining(File.pathSeparator)));
File javaDir = new File(getModule().getProjectDir(), name + "/src/main/java");
File kotlinDir = new File(getModule().getProjectDir(), name + "/src/main/kotlin");
File buildGenDir = new File(getModule().getProjectDir(), name + "/build/gen");
File viewBindingDir = new File(getModule().getProjectDir(), name + "/build/view_binding");
List<File> javaSourceRoots = new ArrayList<>();
if (javaDir.exists()) {
javaSourceRoots.add(javaDir);
}
if (buildGenDir.exists()) {
javaSourceRoots.add(buildGenDir);
}
if (viewBindingDir.exists()) {
javaSourceRoots.add(viewBindingDir);
}
File cacheDir =
new File(getModule().getProjectDir(), name + "/build/kotlin/compileKotlin/cacheable");
List<File> fileList = new ArrayList<>();
if (javaDir.exists()) {
fileList.add(javaDir);
}
if (buildGenDir.exists()) {
fileList.add(buildGenDir);
}
if (viewBindingDir.exists()) {
fileList.add(viewBindingDir);
}
if (kotlinDir.exists()) {
fileList.add(kotlinDir);
}
List<File> plugins = getPlugins();
getLogger().debug("Loading kotlin compiler plugins: " + plugins);
List<String> args = new ArrayList<>();
args.add("dalvikvm");
args.add("-Xcompiler-option");
args.add("--compiler-filter=speed");
args.add("-Xmx256m");
args.add("-cp");
args.add(BuildModule.getKotlinc().getAbsolutePath());
args.add("org.jetbrains.kotlin.cli.jvm.K2JVMCompiler");
args.add("-no-jdk");
args.add("-no-stdlib");
args.add("-no-reflect");
args.add("-jvm-target");
args.add(jvm_target);
args.add("-cp");
args.add(String.join(", ", arguments));
args.add(
"-Xjava-source-roots="
+ String.join(
", ",
javaSourceRoots.stream().map(File::getAbsolutePath).toArray(String[]::new)));
for (File file : fileList) {
args.add(file.getAbsolutePath());
}
args.add("-d");
args.add(out.getAbsolutePath());
args.add("-module-name");
args.add(getModule().getRootFile().getName());
String plugin = "";
String pluginString =
Arrays.toString(plugins.stream().map(File::getAbsolutePath).toArray(String[]::new))
.replace("[", "")
.replace("]", "");
String pluginOptionsString =
Arrays.toString(getPluginOptions()).replace("[", "").replace("]", "");
plugin = pluginString + ":" + (pluginOptionsString.isEmpty() ? ":=" : pluginOptionsString);
args.add("-P");
args.add("plugin:" + plugin);
BinaryExecutor executor = new BinaryExecutor();
executor.setCommands(args);
ExecutionResult result = executor.run();
getLogger().info(executor.getLog().trim());
if (result != null) {
if (result.getExitValue() != 0) {
getLogger().info(result.getOutput().trim());
throw new CompilationFailedException("Compilation failed, see logs for more details");
}
}
}
} catch (Exception e) {
throw new CompilationFailedException(Throwables.getStackTraceAsString(e));
}
}
private String[] appendElement(String[] array, String element) {
String[] newArray = new String[array.length + 1];
System.arraycopy(array, 0, newArray, 0, array.length);
newArray[array.length] = element;
return newArray;
}
private boolean mHasErrors = false;
public void compileJava(
Set<File> javaFiles,
File out,
String name,
List<File> compileClassPath,
List<File> runtimeClassPath)
throws IOException, CompilationFailedException {
if (!out.exists()) {
if (!out.mkdirs()) {
throw new IOException("Failed to create resource output directory");
}
}
try {
File buildSettings =
new File(getModule().getProjectDir(), ".idea/" + name + "_compiler_settings.json");
String content = new String(Files.readAllBytes(Paths.get(buildSettings.getAbsolutePath())));
JSONObject buildSettingsJson = new JSONObject(content);
boolean isCompilerEnabled =
Boolean.parseBoolean(
buildSettingsJson.optJSONObject("java").optString("isCompilerEnabled", "false"));
boolean isSkipJavaTask =
Boolean.parseBoolean(
buildSettingsJson.optJSONObject("java").optString("skipJavaTask", "false"));
String sourceCompatibility =
buildSettingsJson.optJSONObject("java").optString("sourceCompatibility", "1.8");
String targetCompatibility =
buildSettingsJson.optJSONObject("java").optString("targetCompatibility", "1.8");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
BuildModule.getJavac().setReadOnly();
}
if (isSkipJavaTask) {
getLogger().debug("> Task :" + name + ":" + "compileJava SKIPPED");
return;
}
if (!isCompilerEnabled) {
List<File> mFilesToCompile = new ArrayList<>();
mClassCache = getModule().getCache(CACHE_KEY, new Cache<>());
for (Cache.Key<String> key : new HashSet<>(mClassCache.getKeys())) {
if (!mFilesToCompile.contains(key.file.toFile())) {
File file = mClassCache.get(key.file, "class").iterator().next();
deleteAllFiles(file, ".class");
mClassCache.remove(key.file, "class", "dex");
}
}
runtimeClassPath.add(getModule().getBootstrapJarFile());
runtimeClassPath.add(getModule().getLambdaStubsJarFile());
mFilesToCompile.addAll(javaFiles);
List<JavaFileObject> javaFileObjects = new ArrayList<>();
if (mFilesToCompile.isEmpty()) {
getLogger().debug("> Task :" + name + ":" + "compileJava SKIPPED");
return;
} else {
getLogger().debug("> Task :" + name + ":" + "compileJava");
}
List<String> options = new ArrayList<>();
options.add("-proc:none");
options.add("-source");
options.add("1.8");
options.add("-target");
options.add("1.8");
options.add("-Xlint:cast");
options.add("-Xlint:deprecation");
options.add("-Xlint:empty");
options.add("-Xlint" + ":fallthrough");
options.add("-Xlint:finally");
options.add("-Xlint:path");
options.add("-Xlint:unchecked");
options.add("-Xlint" + ":varargs");
options.add("-Xlint:static");
for (File file : mFilesToCompile) {
javaFileObjects.add(
new SimpleJavaFileObject(file.toURI(), JavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors)
throws IOException {
return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}
});
}
DiagnosticListener<JavaFileObject> diagnosticCollector =
diagnostic -> {
switch (diagnostic.getKind()) {
case ERROR:
mHasErrors = true;
getLogger().error(new DiagnosticWrapper(diagnostic));
break;
case WARNING:
getLogger().warning(new DiagnosticWrapper(diagnostic));
}
};
JavacTool tool = JavacTool.create();
JavacFileManager standardJavaFileManager =
tool.getStandardFileManager(
diagnosticCollector, Locale.getDefault(), Charset.defaultCharset());
standardJavaFileManager.setSymbolFileEnabled(false);
standardJavaFileManager.setLocation(
StandardLocation.CLASS_OUTPUT, Collections.singletonList(out));
standardJavaFileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, runtimeClassPath);
standardJavaFileManager.setLocation(StandardLocation.CLASS_PATH, compileClassPath);
standardJavaFileManager.setLocation(StandardLocation.SOURCE_PATH, mFilesToCompile);
JavacTask task =
tool.getTask(
null, standardJavaFileManager, diagnosticCollector, options, null, javaFileObjects);
task.parse();
task.analyze();
task.generate();
if (mHasErrors) {
throw new CompilationFailedException("Compilation failed, check logs for more details");
} else {
getLogger().debug("> Task :" + name + ":" + "classes");
}
} else {
List<File> mFilesToCompile = new ArrayList<>();
mClassCache = getModule().getCache(CACHE_KEY, new Cache<>());
for (Cache.Key<String> key : new HashSet<>(mClassCache.getKeys())) {
if (!mFilesToCompile.contains(key.file.toFile())) {
File file = mClassCache.get(key.file, "class").iterator().next();
deleteAllFiles(file, ".class");
mClassCache.remove(key.file, "class", "dex");
}
}
runtimeClassPath.add(getModule().getBootstrapJarFile());
runtimeClassPath.add(getModule().getLambdaStubsJarFile());
mFilesToCompile.addAll(javaFiles);
if (mFilesToCompile.isEmpty()) {
getLogger().debug("> Task :" + name + ":" + "compileJava SKIPPED");
return;
} else {
getLogger().debug("> Task :" + name + ":" + "compileJava");
}
List<String> args = new ArrayList<>();
args.add("dalvikvm");
args.add("-Xcompiler-option");
args.add("--compiler-filter=speed");
args.add("-Xmx256m");
args.add("-cp");
args.add(BuildModule.getJavac().getAbsolutePath());
args.add("com.sun.tools.javac.MainKt");
args.add("-sourcepath");
args.add(javaFiles.stream().map(File::toString).collect(Collectors.joining(":")));
args.add("-d");
args.add(out.getAbsolutePath());
args.add("-bootclasspath");
args.add(runtimeClassPath.stream().map(File::toString).collect(Collectors.joining(":")));
args.add("-classpath");
args.add(compileClassPath.stream().map(File::toString).collect(Collectors.joining(":")));
args.add("-source");
args.add(sourceCompatibility);
args.add("-target");
args.add(targetCompatibility);
BinaryExecutor executor = new BinaryExecutor();
executor.setCommands(args);
ExecutionResult result = executor.run();
String message = result.getOutput().trim();
if (!message.isEmpty()) {
getLogger().info(message);
}
if (result != null) {
if (result.getExitValue() != 0) {
getLogger().info(executor.getLog().trim());
throw new CompilationFailedException("Compilation failed, see logs for more details");
}
}
}
} catch (Exception e) {
throw new CompilationFailedException(e);
}
}
private void linkRes(File in, String name, File manifest, File assets)
throws CompilationFailedException, IOException {
getLogger().debug("> Task :" + name + ":" + "mergeResources");
List<String> args = new ArrayList<>();
args.add("-I");
args.add(getModule().getBootstrapJarFile().getAbsolutePath());
args.add("--allow-reserved-package-id");
args.add("--no-version-vectors");
args.add("--no-version-transitions");
args.add("--auto-add-overlay");
args.add("--min-sdk-version");
args.add(String.valueOf(getModule().getMinSdk()));
args.add("--target-sdk-version");
args.add(String.valueOf(getModule().getTargetSdk()));
args.add("--proguard");
File buildAar =
new File(getModule().getProjectDir().getAbsolutePath(), name + "/build/bin/aar");
args.add(createNewFile((buildAar), "proguard.txt").getAbsolutePath());
File[] libraryResources = getOutputPath(name).listFiles();
if (libraryResources != null) {
for (File resource : libraryResources) {
if (resource.isDirectory()) {
continue;
}
if (!resource.getName().endsWith(".zip")) {
Log.w(TAG, "Unrecognized file " + resource.getName());
continue;
}
if (resource.length() == 0) {
Log.w(TAG, "Empty zip file " + resource.getName());
}
args.add("-R");
args.add(resource.getAbsolutePath());
}
}
args.add("--java");
File gen = new File(getModule().getProjectDir(), name + "/build/gen");
if (!gen.exists()) {
if (!gen.mkdirs()) {
throw new CompilationFailedException("Failed to create gen folder");
}
}
args.add(gen.getAbsolutePath());
args.add("--manifest");
if (!manifest.exists()) {
throw new IOException("Unable to get project manifest file");
}
args.add(manifest.getAbsolutePath());
args.add("-o");
File buildBin = new File(getModule().getProjectDir().getAbsolutePath(), name + "/build/bin");
File out = new File(buildBin, "generated.aar.res");
args.add(out.getAbsolutePath());
args.add("--output-text-symbols");
File file = new File(buildAar, "R.txt");
Files.deleteIfExists(file.toPath());
if (!file.createNewFile()) {
throw new IOException("Unable to create R.txt file");
}
args.add(file.getAbsolutePath());
for (File library :
getLibraries(
new File(getModule().getProjectDir(), name + "/build/libraries/api_files/libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(new File(getModule().getProjectDir(), name + "/build/libraries/api_libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(
new File(
getModule().getProjectDir(),
name + "/build/libraries/implementation_files/libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(
new File(getModule().getProjectDir(), name + "/build/libraries/implementation_libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(
new File(
getModule().getProjectDir(), name + "/build/libraries/compileOnly_files/libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(
new File(
getModule().getProjectDir(),
name + "/build/libraries/compileOnlyApi_files/libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(
new File(getModule().getProjectDir(), name + "/build/libraries/compileOnly_libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(
new File(getModule().getProjectDir(), name + "/build/libraries/compileOnlyApi_libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(
new File(
getModule().getProjectDir(), name + "/build/libraries/runtimeOnly_files/libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(
new File(
getModule().getProjectDir(),
name + "/build/libraries/runtimeOnlyApi_files/libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(
new File(getModule().getProjectDir(), name + "/build/libraries/runtimeOnly_libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
for (File library :
getLibraries(
new File(getModule().getProjectDir(), name + "/build/libraries/runtimeOnlyApi_libs"))) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
if (assets.exists()) {
args.add("-A");
args.add(assets.getAbsolutePath());
}
int compile = Aapt2Jni.link(args);
List<DiagnosticWrapper> logs = Aapt2Jni.getLogs();
LogUtils.log(logs, getLogger());
if (compile != 0) {
throw new CompilationFailedException("Compilation failed, check logs for more details.");
}
}
private void compileRes(File res, File out, String name)
throws IOException, CompilationFailedException {
if (!out.exists()) {
if (!out.mkdirs()) {
throw new IOException("Failed to create resource output directory");
}
}
List<String> args = new ArrayList<>();
args.add("--dir");
args.add(res.getAbsolutePath());
args.add("-o");
args.add(createNewFile(out, name + "_res.zip").getAbsolutePath());
int compile = Aapt2Jni.compile(args);
List<DiagnosticWrapper> logs = Aapt2Jni.getLogs();
LogUtils.log(logs, getLogger());
if (compile != 0) {
throw new CompilationFailedException("Compilation failed, check logs for more details.");
}
}
private File createNewFile(File parent, String name) throws IOException {
File createdFile = new File(parent, name);
if (!parent.exists()) {
if (!parent.mkdirs()) {
throw new IOException("Unable to create directories");
}
}
if (!createdFile.exists() && !createdFile.createNewFile()) {
throw new IOException("Unable to create file " + name);
}
return createdFile;
}
public static Set<File> getFiles(File dir, String ext) {
Set<File> Files = new HashSet<>();
File[] files = dir.listFiles();
if (files == null) {
return Collections.emptySet();
}
for (File file : files) {
if (file.isDirectory()) {
Files.addAll(getFiles(file, ext));
} else {
if (file.getName().endsWith(ext)) {
Files.add(file);
}
}
}
return Files;
}
private void zipFolder(final Path sourceFolderPath, Path zipPath) throws IOException {
final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath.toFile()));
Files.walkFileTree(
sourceFolderPath,
new SimpleFileVisitor<Path>() {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString()));
Files.copy(file, zos);
zos.closeEntry();
return FileVisitResult.CONTINUE;
}
});
zos.close();
}
private void copyResources(File file, String path) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
copyResources(child, path + "/" + file.getName());
}
}
} else {
File directory = new File(path);
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Failed to create directory " + directory);
}
FileUtils.copyFileToDirectory(file, directory);
}
}
private void deleteAllFiles(File classFile, String ext) throws IOException {
File parent = classFile.getParentFile();
String name = classFile.getName().replace(ext, "");
if (parent != null) {
File[] children =
parent.listFiles((c) -> c.getName().endsWith(ext) && c.getName().contains("$"));
if (children != null) {
for (File child : children) {
if (child.getName().startsWith(name)) {
FileUtils.delete(child);
}
}
}
}
if (classFile.exists()) {
FileUtils.delete(classFile);
}
}
public List<File> getJarFiles(File dir) {
List<File> jarFiles = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".jar")) {
// Check if the JarFile is valid before adding it to the list
if (isJarFileValid(file)) {
jarFiles.add(file);
}
} else if (file.isDirectory()) {
// Recursively add JarFiles from subdirectories
jarFiles.addAll(getJarFiles(file));
}
}
}
return jarFiles;
}
public boolean isJarFileValid(File file) {
String message = "File " + file.getParentFile().getName() + " is corrupt! Ignoring.";
try {
// Try to open the JarFile
JarFile jarFile = new JarFile(file);
// If it opens successfully, close it and return true
jarFile.close();
return true;
} catch (ZipException e) {
// If the JarFile is invalid, it will throw a ZipException
getLogger().warning(message);
return false;
} catch (IOException e) {
// If there is some other error reading the JarFile, return false
getLogger().warning(message);
return false;
}
}
private File getOutputPath(String name) throws IOException {
File file = new File(getModule().getProjectDir(), name + "/build/bin/res");
if (!file.exists()) {
if (!file.mkdirs()) {
throw new IOException("Failed to get resource directory");
}
}
return file;
}
private List<File> getPlugins() {
File pluginDir = new File(getModule().getBuildDirectory(), "plugins");
File[] children = pluginDir.listFiles(c -> c.getName().endsWith(".jar"));
if (children == null) {
return Collections.emptyList();
}
return Arrays.stream(children).collect(Collectors.toList());
}
private String[] getPluginOptions() throws IOException {
File pluginDir = new File(getModule().getBuildDirectory(), "plugins");
File args = new File(pluginDir, "args.txt");
if (!args.exists()) {
return new String[0];
}
String string = FileUtils.readFileToString(args, StandardCharsets.UTF_8);
return string.split(" ");
}
private static class Diagnostic extends DiagnosticWrapper {
private final CompilerMessageSeverity mSeverity;
private final String mMessage;
private final CompilerMessageSourceLocation mLocation;
public Diagnostic(
CompilerMessageSeverity severity, String message, CompilerMessageSourceLocation location) {
mSeverity = severity;
mMessage = message;
if (location == null) {
mLocation =
new CompilerMessageSourceLocation() {
@NonNull
@Override
public String getPath() {
return "UNKNOWN";
}
@Override
public int getLine() {
return 0;
}
@Override
public int getColumn() {
return 0;
}
@Override
public int getLineEnd() {
return 0;
}
@Override
public int getColumnEnd() {
return 0;
}
@Override
public String getLineContent() {
return "";
}
};
} else {
mLocation = location;
}
}
@Override
public File getSource() {
if (mLocation == null || TextUtils.isEmpty(mLocation.getPath())) {
return new File("UNKNOWN");
}
return new File(mLocation.getPath());
}
@Override
public Kind getKind() {
switch (mSeverity) {
case ERROR:
return Kind.ERROR;
case STRONG_WARNING:
return Kind.MANDATORY_WARNING;
case WARNING:
return Kind.WARNING;
case LOGGING:
return Kind.OTHER;
default:
case INFO:
return Kind.NOTE;
}
}
@Override
public long getLineNumber() {
return mLocation.getLine();
}
@Override
public long getColumnNumber() {
return mLocation.getColumn();
}
@Override
public String getMessage(Locale locale) {
return mMessage;
}
}
private class Collector implements MessageCollector {
private final List<Diagnostic> mDiagnostics = new ArrayList<>();
private boolean mHasErrors;
@Override
public void clear() {
mDiagnostics.clear();
}
@Override
public boolean hasErrors() {
return mHasErrors;
}
@Override
public void report(
@NotNull CompilerMessageSeverity severity,
@NotNull String message,
CompilerMessageSourceLocation location) {
if (message.contains("No class roots are found in the JDK path")) {
// Android does not have JDK so its okay to ignore this error
return;
}
Diagnostic diagnostic = new Diagnostic(severity, message, location);
mDiagnostics.add(diagnostic);
switch (severity) {
case ERROR:
mHasErrors = true;
getLogger().error(diagnostic);
break;
case STRONG_WARNING:
case WARNING:
getLogger().warning(diagnostic);
break;
case INFO:
getLogger().info(diagnostic);
break;
default:
getLogger().debug(diagnostic);
}
}
}
}
| 76,330 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
IncrementalAapt2Task.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/incremental/resource/IncrementalAapt2Task.java | package com.tyron.builder.compiler.incremental.resource;
import android.util.Log;
import com.android.tools.aapt2.Aapt2Jni;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.log.LogUtils;
import com.tyron.builder.model.DiagnosticWrapper;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.builder.project.api.Module;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
public class IncrementalAapt2Task extends Task<AndroidModule> {
private static final String TAG = "mergeResources";
private final boolean mGenerateProtoFormat;
public IncrementalAapt2Task(
Project project, AndroidModule module, ILogger logger, boolean generateProtoFormat) {
super(project, module, logger);
mGenerateProtoFormat = generateProtoFormat;
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {}
public void run() throws IOException, CompilationFailedException {
Map<String, List<File>> filesToCompile = getFiles(getModule(), getOutputDirectory(getModule()));
List<File> librariesToCompile = getLibraries();
compileProject(filesToCompile);
compileLibraries(librariesToCompile);
link();
updateJavaFiles();
}
private void updateJavaFiles() {
File genFolder = new File(getModule().getBuildDirectory(), "gen");
if (genFolder.exists()) {
FileUtils.iterateFiles(
genFolder, FileFilterUtils.suffixFileFilter(".java"), TrueFileFilter.INSTANCE)
.forEachRemaining(getModule()::addResourceClass);
}
}
private void compileProject(Map<String, List<File>> files)
throws IOException, CompilationFailedException {
List<String> args = new ArrayList<>();
for (String resourceType : files.keySet()) {
List<File> filesToCompile = files.get(resourceType);
if (filesToCompile != null && !filesToCompile.isEmpty()) {
for (File fileToCompile : filesToCompile) {
args.add(fileToCompile.getAbsolutePath());
}
}
}
args.add("-o");
File outputCompiled = new File(getModule().getBuildDirectory(), "bin/res/compiled");
if (!outputCompiled.exists() && !outputCompiled.mkdirs()) {
throw new IOException("Failed to create compiled directory");
}
args.add(outputCompiled.getAbsolutePath());
int compile = Aapt2Jni.compile(args);
List<DiagnosticWrapper> logs = Aapt2Jni.getLogs();
LogUtils.log(logs, getLogger());
if (compile != 0) {
throw new CompilationFailedException("Compilation failed, check logs for more details.");
}
copyMapToDir(files);
}
private void compileLibraries(List<File> libraries)
throws IOException, CompilationFailedException {
Log.d(TAG, "Compiling libraries.");
File output = new File(getModule().getBuildDirectory(), "bin/res");
if (!output.exists()) {
if (!output.mkdirs()) {
throw new IOException("Failed to create resource output directory");
}
}
for (File file : libraries) {
File parent = file.getParentFile();
if (parent == null) {
throw new IOException("Library folder doesn't exist");
}
File[] files = parent.listFiles();
if (files == null) {
continue;
}
for (File inside : files) {
if (inside.isDirectory() && inside.getName().equals("res")) {
List<String> args = new ArrayList<>();
args.add("--dir");
args.add(inside.getAbsolutePath());
args.add("-o");
args.add(createNewFile(output, parent.getName() + ".zip").getAbsolutePath());
int compile = Aapt2Jni.compile(args);
List<DiagnosticWrapper> logs = Aapt2Jni.getLogs();
LogUtils.log(logs, getLogger());
if (compile != 0) {
throw new CompilationFailedException(
"Compilation failed, check logs for more details.");
}
}
}
}
}
private void link() throws IOException, CompilationFailedException {
Log.d(TAG, "Linking resources");
List<String> args = new ArrayList<>();
args.add("-I");
args.add(getModule().getBootstrapJarFile().getAbsolutePath());
File files = new File(getOutputPath(), "compiled");
args.add("--allow-reserved-package-id");
args.add("--no-version-vectors");
args.add("--no-version-transitions");
args.add("--auto-add-overlay");
args.add("--min-sdk-version");
args.add(String.valueOf(getModule().getMinSdk()));
args.add("--target-sdk-version");
args.add(String.valueOf(getModule().getTargetSdk()));
args.add("--proguard");
args.add(
createNewFile(new File(getModule().getBuildDirectory(), "bin/res"), "generated-rules.txt")
.getAbsolutePath());
File[] libraryResources = getOutputPath().listFiles();
if (libraryResources != null) {
for (File resource : libraryResources) {
if (resource.isDirectory()) {
continue;
}
if (!resource.getName().endsWith(".zip")) {
Log.w(TAG, "Unrecognized file " + resource.getName());
continue;
}
if (resource.length() == 0) {
Log.w(TAG, "Empty zip file " + resource.getName());
}
args.add("-R");
args.add(resource.getAbsolutePath());
}
}
File[] resources = files.listFiles();
if (resources != null) {
for (File resource : resources) {
if (!resource.getName().endsWith(".flat")) {
Log.w(TAG, "Unrecognized file " + resource.getName() + " at compiled directory");
continue;
}
args.add("-R");
args.add(resource.getAbsolutePath());
}
}
args.add("--java");
File gen = new File(getModule().getBuildDirectory(), "gen");
if (!gen.exists()) {
if (!gen.mkdirs()) {
throw new CompilationFailedException("Failed to create gen folder");
}
}
args.add(gen.getAbsolutePath());
args.add("--manifest");
File mergedManifest = new File(getModule().getBuildDirectory(), "bin/AndroidManifest.xml");
if (!mergedManifest.exists()) {
throw new IOException("Unable to get merged manifest file");
}
args.add(mergedManifest.getAbsolutePath());
args.add("-o");
if (mGenerateProtoFormat) {
args.add(getOutputPath().getParent() + "/proto-format.zip");
args.add("--proto-format");
} else {
args.add(getOutputPath().getParent() + "/generated.apk.res");
}
args.add("--output-text-symbols");
File file = new File(getOutputPath(), "R.txt");
Files.deleteIfExists(file.toPath());
if (!file.createNewFile()) {
throw new IOException("Unable to create R.txt file");
}
args.add(file.getAbsolutePath());
for (File library : getModule().getLibraries()) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File assetsDir = new File(parent, "assets");
if (assetsDir.exists()) {
args.add("-A");
args.add(assetsDir.getAbsolutePath());
}
}
if (getModule().getAssetsDirectory().exists()) {
args.add("-A");
args.add(getModule().getAssetsDirectory().getAbsolutePath());
}
int compile = Aapt2Jni.link(args);
List<DiagnosticWrapper> logs = Aapt2Jni.getLogs();
LogUtils.log(logs, getLogger());
if (compile != 0) {
throw new CompilationFailedException("Compilation failed, check logs for more details.");
}
}
/**
* Utility function to get all the files that needs to be recompiled
*
* @return resource files to compile
*/
public static Map<String, List<File>> getFiles(AndroidModule module, File cachedDirectory)
throws IOException {
Map<String, List<ResourceFile>> newFiles = findFiles(module.getAndroidResourcesDirectory());
Map<String, List<ResourceFile>> oldFiles = findFiles(cachedDirectory);
Map<String, List<File>> filesToCompile = new HashMap<>();
for (String resourceType : newFiles.keySet()) {
// if the cache doesn't contain the new files then its considered new
if (!oldFiles.containsKey(resourceType)) {
List<ResourceFile> files = newFiles.get(resourceType);
if (files != null) {
addToMapList(filesToCompile, resourceType, files);
}
continue;
}
// both contain the resource type, compare the contents
if (oldFiles.containsKey(resourceType)) {
List<ResourceFile> newFilesResource = newFiles.get(resourceType);
List<ResourceFile> oldFilesResource = oldFiles.get(resourceType);
if (newFilesResource == null) {
newFilesResource = Collections.emptyList();
}
if (oldFilesResource == null) {
oldFilesResource = Collections.emptyList();
}
addToMapList(
filesToCompile, resourceType, getModifiedFiles(newFilesResource, oldFilesResource));
}
}
for (String resourceType : oldFiles.keySet()) {
// if the new files doesn't contain the old file then its deleted
if (!newFiles.containsKey(resourceType)) {
List<ResourceFile> files = oldFiles.get(resourceType);
if (files != null) {
for (File file : files) {
if (!file.delete()) {
throw new IOException("Failed to delete file " + file);
}
}
}
}
}
return filesToCompile;
}
/**
* Utility method to add a list of files to a map, if it doesn't exist, it creates a new one
*
* @param map The map to add to
* @param key Key to add the value
* @param values The list of files to add
*/
public static void addToMapList(
Map<String, List<File>> map, String key, List<ResourceFile> values) {
List<File> mapValues = map.get(key);
if (mapValues == null) {
mapValues = new ArrayList<>();
}
mapValues.addAll(values);
map.put(key, mapValues);
}
private void copyMapToDir(Map<String, List<File>> map) throws IOException {
File output = new File(getModule().getBuildDirectory(), "intermediate/resources");
if (!output.exists()) {
if (!output.mkdirs()) {
throw new IOException("Failed to create intermediate directory");
}
}
for (String resourceType : map.keySet()) {
File outputDir = new File(output, resourceType);
if (!outputDir.exists()) {
if (!outputDir.mkdir()) {
throw new IOException("Failed to create output directory for " + outputDir);
}
}
List<File> files = map.get(resourceType);
if (files != null) {
for (File file : files) {
File copy = new File(outputDir, file.getName());
if (copy.exists()) {
FileUtils.deleteQuietly(copy);
}
FileUtils.copyFileToDirectory(file, outputDir, false);
}
}
}
}
/** Utility method to compare to list of files */
public static List<ResourceFile> getModifiedFiles(
List<ResourceFile> newFiles, List<ResourceFile> oldFiles) throws IOException {
List<ResourceFile> resourceFiles = new ArrayList<>();
for (ResourceFile newFile : newFiles) {
if (!oldFiles.contains(newFile)) {
resourceFiles.add(newFile);
} else {
File oldFile = oldFiles.get(oldFiles.indexOf(newFile));
if (contentModified(newFile, oldFile)) {
resourceFiles.add(newFile);
if (!oldFile.delete()) {
throw new IOException("Failed to delete file " + oldFile.getName());
}
}
oldFiles.remove(oldFile);
}
}
for (ResourceFile removedFile : oldFiles) {
if (!removedFile.delete()) {
throw new IOException("Failed to delete old file " + removedFile);
}
}
return resourceFiles;
}
private static boolean contentModified(File newFile, File oldFile) {
if (!oldFile.exists() || !newFile.exists()) {
return true;
}
if (newFile.length() != oldFile.length()) {
return true;
}
return newFile.lastModified() > oldFile.lastModified();
}
/**
* Returns a map of resource type, and the files for a given resource directory
*
* @param file res directory
* @return Map of resource type and the files corresponding to it
*/
public static Map<String, List<ResourceFile>> findFiles(File file) {
File[] children = file.listFiles();
if (children == null) {
return Collections.emptyMap();
}
Map<String, List<ResourceFile>> map = new HashMap<>();
for (File child : children) {
if (!file.isDirectory()) {
continue;
}
String resourceType = child.getName();
File[] resourceFiles = child.listFiles();
List<File> files;
if (resourceFiles == null) {
files = Collections.emptyList();
} else {
files = Arrays.asList(resourceFiles);
}
map.put(
resourceType, files.stream().map(ResourceFile::fromFile).collect(Collectors.toList()));
}
return map;
}
/**
* Returns the list of resource directories of libraries that needs to be compiled It determines
* whether the library should be compiled by checking the build/bin/res folder, if it contains a
* zip file with its name, then its most likely the same library
*/
private List<File> getLibraries() throws IOException {
File resDir = new File(getModule().getBuildDirectory(), "bin/res");
if (!resDir.exists()) {
if (!resDir.mkdirs()) {
throw new IOException("Failed to create resource directory");
}
}
List<File> libraries = new ArrayList<>();
for (File library : getModule().getLibraries()) {
File parent = library.getParentFile();
if (parent != null) {
if (!new File(parent, "res").exists()) {
// we don't need to check it if it has no resource directory
continue;
}
File check = new File(resDir, parent.getName() + ".zip");
if (!check.exists()) {
libraries.add(library);
}
}
}
return libraries;
}
private File createNewFile(File parent, String name) throws IOException {
File createdFile = new File(parent, name);
if (!parent.exists()) {
if (!parent.mkdirs()) {
throw new IOException("Unable to create directories");
}
}
if (!createdFile.exists() && !createdFile.createNewFile()) {
throw new IOException("Unable to create file " + name);
}
return createdFile;
}
/**
* Return the output directory of where to stored cached files
*
* @param module The module
* @return The cached directory
* @throws IOException If the directory does not exist and cannot be created
*/
public static File getOutputDirectory(Module module) throws IOException {
File intermediateDirectory = new File(module.getBuildDirectory(), "intermediate");
if (!intermediateDirectory.exists()) {
if (!intermediateDirectory.mkdirs()) {
throw new IOException("Failed to create intermediate directory");
}
}
File resourceDirectory = new File(intermediateDirectory, "resources");
if (!resourceDirectory.exists()) {
if (!resourceDirectory.mkdirs()) {
throw new IOException("Failed to create resource directory");
}
}
return resourceDirectory;
}
private File getOutputPath() throws IOException {
File file = new File(getModule().getBuildDirectory(), "bin/res");
if (!file.exists()) {
if (!file.mkdirs()) {
throw new IOException("Failed to get resource directory");
}
}
return file;
}
}
| 16,203 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ResourceFile.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/incremental/resource/ResourceFile.java | package com.tyron.builder.compiler.incremental.resource;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.io.File;
import java.net.URI;
/** Used by {@link IncrementalAapt2Task} to find differences between two files */
public class ResourceFile extends File {
public ResourceFile(@NonNull String pathname) {
super(pathname);
}
public ResourceFile(@Nullable String parent, @NonNull String child) {
super(parent, child);
}
public ResourceFile(@Nullable File parent, @NonNull String child) {
super(parent, child);
}
public ResourceFile(@NonNull URI uri) {
super(uri);
}
public static ResourceFile fromFile(File file) {
return new ResourceFile(file.getAbsolutePath());
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof ResourceFile) {
return ((ResourceFile) obj).getName().equals(this.getName());
}
return false;
}
}
| 947 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
RunTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/java/RunTask.java | package com.tyron.builder.compiler.java;
import android.os.Build;
import com.tyron.builder.BuildModule;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.common.util.BinaryExecutor;
import com.tyron.common.util.ExecutionResult;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class RunTask extends Task<AndroidModule> {
private static final String TAG = "run";
private File mApkFile;
private File zipFile;
public RunTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
mApkFile = new File(getModule().getBuildDirectory(), "bin/generated.apk");
if (!mApkFile.exists()) {
throw new IOException("Unable to find generated file in projects build path");
}
zipFile = new File(mApkFile.getParent(), "classes.dex.zip");
mApkFile.renameTo(zipFile);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
mApkFile.setReadOnly();
}
if (!zipFile.exists()) {
throw new IOException("Unable to find classes.dex.zip File in projects build path");
}
}
@Override
public void run() throws IOException, CompilationFailedException {
String mainClass = getModule().getMainClass();
if (mainClass != null) {
List<String> args = new ArrayList<>();
args.add("dalvikvm");
args.add("-Xcompiler-option");
args.add("--compiler-filter=speed");
args.add("-Xmx256m");
args.add("-Djava.io.tmpdir=" + BuildModule.getContext().getCacheDir().getAbsolutePath());
args.add("-cp");
args.add(zipFile.getAbsolutePath());
args.add(mainClass);
BinaryExecutor executor = new BinaryExecutor();
executor.setCommands(args);
ExecutionResult result = executor.run();
if (result != null) {
if (result.getExitValue() == 0) {
getLogger().debug(result.getOutput());
} else {
getLogger().error("Execution failed with exit code " + result.getExitValue() + ":");
getLogger().error(executor.getLog());
}
}
} else {
throw new CompilationFailedException(
"Unable to find mainClass in project's build.gradle file.");
}
}
}
| 2,613 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CheckLibrariesTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/java/CheckLibrariesTask.java | package com.tyron.builder.compiler.java;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.ScopeType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.model.Library;
import com.tyron.builder.model.ModuleSettings;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.builder.project.api.Module;
import com.tyron.common.util.Decompress;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
/** Task responsible for copying aars/jars from libraries to build/libs */
public class CheckLibrariesTask extends Task<JavaModule> {
public CheckLibrariesTask(Project project, JavaModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return "checkLibraries";
}
@Override
public void prepare(BuildType type) throws IOException {}
@Override
public void run() throws IOException, CompilationFailedException {
checkLibraries(
getModule(),
getModule().getRootFile(),
getLogger(),
getModule().getGradleFile(),
getModule().getRootFile().getName());
List<String> projects = new ArrayList<>();
projects.addAll(getModule().getAllProjects(getModule().getGradleFile()));
Set<String> resolvedProjects = new HashSet<>();
while (!projects.isEmpty()) {
String include = projects.remove(0);
if (resolvedProjects.contains(include)) {
continue;
}
resolvedProjects.add(include);
File gradleFile = new File(getModule().getProjectDir(), include + "/build.gradle");
if (gradleFile.exists()) {
List<String> includedInBuildGradle = getModule().getAllProjects(gradleFile);
if (!includedInBuildGradle.isEmpty()) {
projects.addAll(includedInBuildGradle);
}
File idea = new File(getModule().getProjectDir(), ".idea");
File includeName = new File(getModule().getProjectDir(), include);
String root = include.replaceFirst("/", "").replaceAll("/", ":");
getLogger().debug("> Task :" + root + ":" + "checkingLibraries");
try {
checkLibraries(getModule(), includeName, getLogger(), gradleFile, root);
createCompilerSettings(idea, include);
} catch (IOException e) {
}
}
}
}
private void createCompilerSettings(File idea, String name) {
File buildSettings = new File(idea, name + "_compiler_settings.json");
if (!buildSettings.exists()) {
try {
JSONObject javaSettings = new JSONObject();
javaSettings.put("isCompilerEnabled", "false");
javaSettings.put("sourceCompatibility", "1.8");
javaSettings.put("targetCompatibility", "1.8");
JSONObject kotlinSettings = new JSONObject();
kotlinSettings.put("isCompilerEnabled", "false");
kotlinSettings.put("jvmTarget", "1.8");
// kotlinSettings.put("languageVersion", "2.1");
JSONObject buildSettingsJson = new JSONObject();
buildSettingsJson.put("java", javaSettings);
buildSettingsJson.put("kotlin", kotlinSettings);
FileWriter fileWriter = new FileWriter(buildSettings, true);
fileWriter.write(buildSettingsJson.toString(1));
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void checkLibraries(
JavaModule project, File root, ILogger logger, File gradleFile, String name)
throws IOException {
File idea = new File(project.getProjectDir(), ".idea");
ScopeType api = ScopeType.API;
String scopeTypeApi = api.getStringValue();
checkLibraries(project, root, idea, logger, gradleFile, scopeTypeApi);
ScopeType natives = ScopeType.NATIVES;
String scopeTypeNatives = natives.getStringValue();
checkLibraries(project, root, idea, logger, gradleFile, scopeTypeNatives);
ScopeType implementation = ScopeType.IMPLEMENTATION;
String scopeTypeImplementation = implementation.getStringValue();
checkLibraries(project, root, idea, logger, gradleFile, scopeTypeImplementation);
ScopeType compileOnly = ScopeType.COMPILE_ONLY;
String scopeTypeCompileOnly = compileOnly.getStringValue();
checkLibraries(project, root, idea, logger, gradleFile, scopeTypeCompileOnly);
ScopeType runtimeOnly = ScopeType.RUNTIME_ONLY;
String scopeTypeRuntimeOnly = runtimeOnly.getStringValue();
checkLibraries(project, root, idea, logger, gradleFile, scopeTypeRuntimeOnly);
ScopeType compileOnlyApi = ScopeType.COMPILE_ONLY_API;
String scopeTypeCompileOnlyApi = compileOnlyApi.getStringValue();
checkLibraries(project, root, idea, logger, gradleFile, scopeTypeCompileOnlyApi);
ScopeType runtimeOnlyApi = ScopeType.RUNTIME_ONLY_API;
String scopeTypeRuntimeOnlyApi = runtimeOnlyApi.getStringValue();
checkLibraries(project, root, idea, logger, gradleFile, scopeTypeRuntimeOnlyApi);
}
// checkLibraries
private void checkLibraries(
JavaModule project, File root, File idea, ILogger logger, File gradleFile, String scope)
throws IOException {
Set<Library> libraries = new HashSet<>();
Map<String, Library> fileLibsHashes = new HashMap<>();
Map<String, Library> md5Map = new HashMap<>();
AbstractMap.SimpleEntry<ArrayList<String>, ArrayList<String>> result =
project.extractListDirAndIncludes(gradleFile, scope);
if (result != null) {
ArrayList<String> dirValue = result.getKey();
ArrayList<String> includeValues = result.getValue();
if (dirValue != null && includeValues != null) {
for (int i = 0; i < dirValue.size(); i++) {
String dir = dirValue.get(i);
String include = includeValues.get(i);
fileLibsHashes =
new HashMap<>(
checkDirLibraries(fileLibsHashes, logger, new File(root, dir), include, scope));
}
}
}
List<AbstractMap.SimpleEntry<String, ArrayList<String>>> results =
project.extractDirAndIncludes(gradleFile, scope);
if (results != null) {
for (AbstractMap.SimpleEntry<String, ArrayList<String>> entry : results) {
String dir = entry.getKey();
ArrayList<String> includes = entry.getValue();
if (dir != null && includes != null) {
fileLibsHashes =
new HashMap<>(
checkDirIncludeLibraries(
fileLibsHashes, logger, new File(root, dir), includes, scope));
}
}
}
libraries =
new HashSet<>(
parseLibraries(
libraries,
new File(idea, root.getName() + "_" + scope + "_libraries.json"),
root.getName()));
if (!scope.equals(ScopeType.NATIVES.getStringValue())) {
md5Map =
new HashMap<>(
checkLibraries(
md5Map,
libraries,
fileLibsHashes,
new File(root, "build/libraries/" + scope + "_files/libs")));
saveLibraryToProject(
project,
new File(root, "build/libraries/" + scope + "_files/libs"),
new File(idea, root.getName() + "_" + scope + "_libraries.json"),
scope + "Files",
md5Map,
fileLibsHashes);
}
md5Map.clear();
fileLibsHashes.clear();
libraries.clear();
}
public Map<String, Library> checkDirLibraries(
Map<String, Library> fileLibsHashes, ILogger logger, File dir, String include, String scope) {
try {
ZipFile zipFile = new ZipFile(new File(dir, include));
Library library = new Library();
library.setSourceFile(new File(dir, include));
fileLibsHashes.put(calculateMD5(new File(dir, include)), library);
} catch (IOException e) {
String message = "File " + include + " is corrupt! Ignoring.";
logger.warning(message);
}
return fileLibsHashes;
}
public Map<String, Library> checkDirIncludeLibraries(
Map<String, Library> fileLibsHashes,
ILogger logger,
File dir,
ArrayList<String> includes,
String scope) {
for (String ext : includes) {
File[] fileLibraries = dir.listFiles(c -> c.getName().endsWith(ext));
if (fileLibraries != null) {
for (File fileLibrary : fileLibraries) {
try {
ZipFile zipFile = new ZipFile(fileLibrary);
Library library = new Library();
library.setSourceFile(fileLibrary);
fileLibsHashes.put(calculateMD5(fileLibrary), library);
} catch (IOException e) {
String message = "File " + fileLibrary + " is corrupt! Ignoring.";
logger.warning(message);
}
}
}
}
return fileLibsHashes;
}
public Set<Library> parseLibraries(Set<Library> libraries, File file, String scope) {
ModuleSettings myModuleSettings = new ModuleSettings(file);
String librariesString = myModuleSettings.getString(scope + "_libraries", "[]");
try {
List<Library> parsedLibraries =
new Gson().fromJson(librariesString, new TypeToken<List<Library>>() {}.getType());
if (parsedLibraries != null) {
/*for (Library parsedLibrary : parsedLibraries) {
if (!libraries.contains(parsedLibrary)) {
Log.d("LibraryCheck", "Removed library" + parsedLibrary);
} else {
libraries.add(parsedLibrary);
}
}*/
libraries.addAll(parsedLibraries);
}
} catch (Exception ignore) {
}
return libraries;
}
public Map<String, Library> checkLibraries(
Map<String, Library> md5Map,
Set<Library> libraries,
Map<String, Library> fileLibsHashes,
File libs)
throws IOException {
libraries.forEach(it -> md5Map.put(calculateMD5(it.getSourceFile()), it));
if (!libs.exists()) {
if (!libs.mkdirs()) {}
}
File[] buildLibraryDirs = libs.listFiles(File::isDirectory);
if (buildLibraryDirs != null) {
for (File libraryDir : buildLibraryDirs) {
String md5Hash = libraryDir.getName();
if (!md5Map.containsKey(md5Hash) && !fileLibsHashes.containsKey(md5Hash)) {
FileUtils.deleteDirectory(libraryDir);
Log.d("LibraryCheck", "Deleting contents of " + md5Hash);
}
}
}
return md5Map;
}
private void saveLibraryToProject(
Module module,
File libs,
File file,
String scope,
Map<String, Library> libraries,
Map<String, Library> fileLibraries)
throws IOException {
Map<String, Library> combined = new HashMap<>();
combined.putAll(libraries);
combined.putAll(fileLibraries);
getModule().putLibraryHashes(combined);
for (Map.Entry<String, Library> entry : combined.entrySet()) {
String hash = entry.getKey();
Library library = entry.getValue();
File libraryDir = new File(libs, hash);
if (!libraryDir.exists()) {
libraryDir.mkdir();
} else {
continue;
}
if (library.getSourceFile().getName().endsWith(".jar")) {
FileUtils.copyFileToDirectory(library.getSourceFile(), libraryDir);
File jar = new File(libraryDir, library.getSourceFile().getName());
jar.renameTo(new File(libraryDir, "classes.jar"));
jar = new File(libraryDir, "classes.jar");
if (scope.equals(ScopeType.NATIVES.getStringValue())) {
String pattern = "-natives-(.*)\\.jar";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(library.getSourceFile().getName());
if (m.find()) {
String arch = m.group(1);
if (arch != null) {
File archDir = new File(libraryDir, "jni/" + arch);
if (!archDir.exists()) {
archDir.mkdirs();
}
Decompress.unzip(jar.getAbsolutePath(), archDir.getAbsolutePath());
}
}
}
} else if (library.getSourceFile().getName().endsWith(".aar")) {
Decompress.unzip(library.getSourceFile().getAbsolutePath(), libraryDir.getAbsolutePath());
}
}
saveToGson(combined.values(), file, scope);
}
private void saveToGson(Collection values, File file, String scope) {
ModuleSettings myModuleSettings = new ModuleSettings(file);
String librariesString = new Gson().toJson(values);
myModuleSettings.edit().putString(scope + "_libraries", librariesString).apply();
}
public static String calculateMD5(File updateFile) {
InputStream is;
try {
is = new FileInputStream(updateFile);
} catch (FileNotFoundException e) {
Log.e("calculateMD5", "Exception while getting FileInputStream", e);
return null;
}
return calculateMD5(is);
}
public static String calculateMD5(InputStream is) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
Log.e("calculateMD5", "Exception while getting Digest", e);
return null;
}
byte[] buffer = new byte[8192];
int read;
try {
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
String output = bigInt.toString(16);
// Fill to 32 chars
output = String.format("%32s", output).replace(' ', '0');
return output;
} catch (IOException e) {
throw new RuntimeException("Unable to process file for MD5", e);
} finally {
try {
is.close();
} catch (IOException e) {
Log.e("calculateMD5", "Exception on closing MD5 input stream", e);
}
}
}
}
| 14,533 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
BuildJarTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/jar/BuildJarTask.java | package com.tyron.builder.compiler.jar;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.internal.jar.AssembleJar;
import com.tyron.builder.internal.jar.JarOptionsImpl;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;
public class BuildJarTask extends Task<JavaModule> {
private static final String TAG = "jar";
public BuildJarTask(Project project, JavaModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {}
@Override
public void run() throws IOException, CompilationFailedException {
File javaClasses = new File(getModule().getRootFile(), "build/bin/java/classes");
File kotlinClasses = new File(getModule().getRootFile(), "build/bin/kotlin/classes");
File out =
new File(
getModule().getRootFile(),
"build/outputs/jar/" + getModule().getRootFile().getName() + ".jar");
List<File> inputFolders = new ArrayList<>();
inputFolders.add(javaClasses);
inputFolders.add(kotlinClasses);
assembleJar(inputFolders, out);
}
public void assembleJar(File input, File out) throws IOException, CompilationFailedException {
if (!out.getParentFile().exists()) {
if (!out.getParentFile().mkdirs()) {
throw new IOException("Failed to create resource output directory");
}
}
AssembleJar assembleJar = new AssembleJar(false);
assembleJar.setOutputFile(out);
assembleJar.setJarOptions(new JarOptionsImpl(new Attributes()));
assembleJar.createJarArchive(input);
}
public void assembleJar(List<File> inputFolders, File out)
throws IOException, CompilationFailedException {
if (!out.getParentFile().exists()) {
if (!out.getParentFile().mkdirs()) {
throw new IOException("Failed to create resource output directory");
}
}
AssembleJar assembleJar = new AssembleJar(false);
assembleJar.setOutputFile(out);
assembleJar.setJarOptions(new JarOptionsImpl(new Attributes()));
assembleJar.createJarArchive(inputFolders);
}
}
| 2,462 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
MergeSymbolsTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/symbol/MergeSymbolsTask.java | package com.tyron.builder.compiler.symbol;
import android.util.Log;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.compiler.resource.AAPT2Compiler;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.builder.project.cache.CacheHolder;
import com.tyron.common.util.Cache;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import org.apache.commons.io.FileUtils;
/** Class that loads R.txt files generated by AAPT/AAPT2 and converts them to R.java class files */
public class MergeSymbolsTask extends Task<AndroidModule> {
public static final CacheHolder.CacheKey<Void, Void> CACHE_KEY =
new CacheHolder.CacheKey<>("mergeSymbolsCache");
private File mSymbolOutputDir;
private File mFullResourceFile;
public MergeSymbolsTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return "symbolProcessor";
}
@Override
public void prepare(BuildType type) throws IOException {
mSymbolOutputDir = new File(getModule().getBuildDirectory(), "gen");
mFullResourceFile = new File(getModule().getBuildDirectory(), "bin/res/R.txt");
}
@Override
public void run() throws IOException, CompilationFailedException {
Cache<Void, Void> cache = getModule().getCache(CACHE_KEY, new Cache<>());
SymbolLoader fullSymbolValues = null;
Multimap<String, SymbolLoader> libMap = ArrayListMultimap.create();
List<File> RFiles = new ArrayList<>();
for (File library : getModule().getLibraries()) {
File parent = library.getParentFile();
if (parent == null) {
getLogger().error("Unable to access parent directory for " + library);
continue;
}
String packageName = AAPT2Compiler.getPackageName(new File(parent, "AndroidManifest.xml"));
if (packageName == null) {
continue;
}
if (packageName.equals(getModule().getNameSpace())) {
// only generate libraries
continue;
}
File rFile = new File(parent, "R.txt");
if (!rFile.exists()) {
continue;
}
RFiles.add(rFile);
}
for (Cache.Key<Void> key : new HashSet<>(cache.getKeys())) {
if (!RFiles.contains(key.file.toFile())) {
Log.d(
"MergeSymbolsTask",
"Found deleted resource file, removing "
+ key.file.toFile().getName()
+ " on the cache.");
cache.remove(key.file, (Void) null);
FileUtils.delete(key.file.toFile());
}
}
for (File rFile : RFiles) {
if (!cache.needs(rFile.toPath(), null)) {
continue;
}
File parent = rFile.getParentFile();
if (parent == null) {
getLogger().error("Unable to access parent directory for " + rFile);
continue;
}
String packageName = AAPT2Compiler.getPackageName(new File(parent, "AndroidManifest.xml"));
if (packageName == null) {
continue;
}
if (fullSymbolValues == null) {
fullSymbolValues = new SymbolLoader(mFullResourceFile, getLogger());
fullSymbolValues.load();
}
SymbolLoader libSymbols = new SymbolLoader(rFile, getLogger());
libSymbols.load();
libMap.put(packageName, libSymbols);
}
// now loop on all the package name, merge all the symbols to write, and write them
for (String packageName : libMap.keySet()) {
Collection<SymbolLoader> symbols = libMap.get(packageName);
SymbolWriter writer =
new SymbolWriter(
mSymbolOutputDir.getAbsolutePath(), packageName, fullSymbolValues, getModule());
for (SymbolLoader loader : symbols) {
writer.addSymbolsToWrite(loader);
}
writer.write();
}
for (File file : RFiles) {
cache.load(file.toPath(), null, null);
}
}
}
| 4,245 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
SymbolLoader.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/symbol/SymbolLoader.java | package com.tyron.builder.compiler.symbol;
import com.google.common.base.Charsets;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.common.io.Files;
import com.tyron.builder.log.ILogger;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class SymbolLoader {
private final File mSymbolFile;
private Table<String, String, SymbolEntry> mSymbols;
private final ILogger mLogger;
public static class SymbolEntry {
private final String mName;
private final String mType;
private final String mValue;
public SymbolEntry(String name, String type, String value) {
mName = name;
mType = type;
mValue = value;
}
public String getValue() {
return mValue;
}
public String getName() {
return mName;
}
public String getType() {
return mType;
}
}
public SymbolLoader(Table<String, String, SymbolEntry> symbols) {
this(null, null);
mSymbols = symbols;
}
public SymbolLoader(File symbolFile, ILogger logger) {
mSymbolFile = symbolFile;
mLogger = logger;
}
public void load() throws IOException {
if (mSymbolFile == null) {
throw new IOException(
"Symbol file is null. load() should not be called when"
+ "the symbols are injected at runtime.");
}
List<String> lines = Files.readLines(mSymbolFile, Charsets.UTF_8);
mSymbols = HashBasedTable.create();
int lineIndex = 1;
String line = null;
try {
final int count = lines.size();
for (; lineIndex <= count; lineIndex++) {
line = lines.get(lineIndex - 1);
// format is "<type> <class> <name> <value>"
// don't want to split on space as value could contain spaces.
int pos = line.indexOf(' ');
String type = line.substring(0, pos);
int pos2 = line.indexOf(' ', pos + 1);
String className = line.substring(pos + 1, pos2);
int pos3 = line.indexOf(' ', pos2 + 1);
String name = line.substring(pos2 + 1, pos3);
String value = line.substring(pos3 + 1);
mSymbols.put(className, name, new SymbolEntry(name, type, value));
}
} catch (IndexOutOfBoundsException e) {
if (mLogger != null) {
String s =
String.format(
Locale.ENGLISH,
"File format error reading %s\tline %d: '%s'",
mSymbolFile.getAbsolutePath(),
lineIndex,
line);
mLogger.error(s);
throw new IOException(s, e);
}
}
}
Table<String, String, SymbolEntry> getSymbols() {
return mSymbols;
}
}
| 2,725 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
SymbolWriter.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/symbol/SymbolWriter.java | package com.tyron.builder.compiler.symbol;
import com.google.common.base.Splitter;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Table;
import com.tyron.builder.project.api.AndroidModule;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FileUtils;
/**
* A class to write R.java classes based on data read from text symbol files generated by AAPT/AAPT2
* with the --output-text-symbols option.
*/
public class SymbolWriter {
private final String mOutFolder;
private final String mPackageName;
private final List<SymbolLoader> mSymbols = Lists.newArrayList();
private final SymbolLoader mValues;
private final AndroidModule mProject;
public SymbolWriter(
String outFolder, String packageName, SymbolLoader values, AndroidModule project) {
mOutFolder = outFolder;
mPackageName = packageName;
mValues = values;
mProject = project;
}
public void addSymbolsToWrite(SymbolLoader symbols) {
mSymbols.add(symbols);
}
private Table<String, String, SymbolLoader.SymbolEntry> getAllSymbols() {
Table<String, String, SymbolLoader.SymbolEntry> symbols = HashBasedTable.create();
for (SymbolLoader symbolLoader : mSymbols) {
symbols.putAll(symbolLoader.getSymbols());
}
return symbols;
}
public String getString() throws IOException {
try (StringWriter writer = new StringWriter()) {
writer.write("/* AUTO-GENERATED FILE. DO NOT MODIFY. \n");
writer.write(" *\n");
writer.write(" * This class was automatically generated by the\n");
writer.write(" * aapt tool from the resource data it found. It\n");
writer.write(" * should not be modified by hand.\n");
writer.write(" */\n");
writer.write("package ");
writer.write(mPackageName);
writer.write(";\n\npublic final class R {\n");
Table<String, String, SymbolLoader.SymbolEntry> symbols = getAllSymbols();
Table<String, String, SymbolLoader.SymbolEntry> values = mValues.getSymbols();
Set<String> rowSet = symbols.rowKeySet();
List<String> rowList = Lists.newArrayList(rowSet);
Collections.sort(rowList);
for (String row : rowList) {
writer.write("\tpublic static final class ");
writer.write(row);
writer.write(" {\n");
Map<String, SymbolLoader.SymbolEntry> rowMap = symbols.row(row);
Set<String> symbolSet = rowMap.keySet();
ArrayList<String> symbolList = Lists.newArrayList(symbolSet);
Collections.sort(symbolList);
for (String symbolName : symbolList) {
// get the matching SymbolEntry from the values Table.
SymbolLoader.SymbolEntry value = values.get(row, symbolName);
if (value != null) {
writer.write("\t\tpublic static final ");
writer.write(value.getType());
writer.write(" ");
writer.write(value.getName());
writer.write(" = ");
writer.write(value.getValue());
writer.write(";\n");
}
}
writer.write("\t}\n");
}
writer.write("}\n");
return writer.toString();
}
}
public void write() throws IOException {
Splitter splitter = Splitter.on('.');
Iterable<String> folders = splitter.split(mPackageName);
File file = new File(mOutFolder);
for (String folder : folders) {
file = new File(file, folder);
}
boolean newFile = false;
if (!file.exists()) {
newFile = true;
if (!file.mkdirs()) {
throw new IOException("Unable to create resource directories for " + file);
}
}
file = new File(file, "R.java");
String contents = getString();
if (newFile || !file.exists()) {
if (!file.createNewFile()) {
throw new IOException("Unable to create R.txt file");
}
FileUtils.writeStringToFile(file, contents, Charset.defaultCharset());
} else {
String oldContents;
try {
oldContents = FileUtils.readFileToString(file, Charset.defaultCharset());
} catch (IOException e) {
oldContents = "";
}
if (!oldContents.equals(contents)) {
FileUtils.writeStringToFile(file, contents, Charset.defaultCharset());
}
}
mProject.addResourceClass(file);
}
}
| 4,550 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
GenerateReleaseBuildConfigTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/buildconfig/GenerateReleaseBuildConfigTask.java | package com.tyron.builder.compiler.buildconfig;
import android.util.Log;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
public class GenerateReleaseBuildConfigTask extends Task<AndroidModule> {
private static final String TAG = "generateReleaseBuildConfig";
public GenerateReleaseBuildConfigTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
getModule().getJavaFiles();
getModule().getKotlinFiles();
}
@Override
public void run() throws IOException, CompilationFailedException {
GenerateBuildConfig();
}
private void GenerateBuildConfig() throws IOException {
Log.d(TAG, "Generating BuildConfig.java");
String packageName = getApplicationId();
File packageDir =
new File(getModule().getBuildDirectory() + "/gen", packageName.replace('.', '/'));
File buildConfigClass = new File(packageDir, "/BuildConfig.java");
if (packageDir.exists()) {
} else {
packageDir.mkdirs();
}
File parentDir = buildConfigClass.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
if (!buildConfigClass.exists() && !buildConfigClass.createNewFile()) {
throw new IOException("Unable to generate BuildConfig.java");
}
String content = parseString(getModule().getGradleFile());
if (content != null) {
boolean isAndroidLibrary = false;
if (content.contains("com.android.library")) {
isAndroidLibrary = true;
}
if (!isAndroidLibrary) {
String buildConfigString =
"/**"
+ "\n"
+ "* Automatically generated file. DO NOT MODIFY"
+ "\n"
+ "*/"
+ "\n"
+ "package "
+ packageName
+ ";\n"
+ "\n"
+ "public final class BuildConfig {"
+ "\n"
+ " public static final boolean DEBUG = "
+ "false"
+ ";\n"
+ " public static final String APPLICATION_ID = "
+ "\"$package_name\"".replace("$package_name", packageName)
+ ";\n"
+ " public static final String BUILD_TYPE = "
+ "\"release\""
+ ";\n"
+ " public static final int VERSION_CODE = "
+ getModule().getVersionCode()
+ ";\n"
+ " public static final String VERSION_NAME = "
+ "\"$version_name\"".replace("$version_name", getModule().getVersionName())
+ ";\n"
+ "}\n";
FileUtils.writeStringToFile(buildConfigClass, buildConfigString, Charset.defaultCharset());
} else {
String buildConfigString =
"/**"
+ "\n"
+ "* Automatically generated file. DO NOT MODIFY"
+ "\n"
+ "*/"
+ "\n"
+ "package "
+ packageName
+ ";\n"
+ "\n"
+ "public final class BuildConfig {"
+ "\n"
+ " public static final boolean DEBUG = "
+ "false"
+ ";\n"
+ " public static final String LIBRARY_PACKAGE_NAME = "
+ "\"$package_name\"".replace("$package_name", packageName)
+ ";\n"
+ " public static final String BUILD_TYPE = "
+ "\"release\""
+ ";\n"
+ "}\n";
FileUtils.writeStringToFile(buildConfigClass, buildConfigString, Charset.defaultCharset());
}
}
}
public void GenerateBuildConfig(String packageName, File genDir) throws IOException {
Log.d(TAG, "Generating BuildConfig.java");
if (packageName == null) {
throw new IOException("Unable to find namespace in build.gradle file");
}
File dir = new File(genDir, packageName.replace('.', '/'));
File buildConfigClass = new File(dir, "/BuildConfig.java");
if (genDir.exists() || dir.exists()) {
} else {
genDir.mkdirs();
dir.mkdirs();
}
File parentDir = buildConfigClass.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
if (!buildConfigClass.exists() && !buildConfigClass.createNewFile()) {
throw new IOException("Unable to generate BuildConfig.java");
}
String buildConfigString =
"/**"
+ "\n"
+ "* Automatically generated file. DO NOT MODIFY"
+ "\n"
+ "*/"
+ "\n"
+ "package "
+ packageName
+ ";\n"
+ "\n"
+ "public final class BuildConfig {"
+ "\n"
+ " public static final boolean DEBUG = "
+ "false"
+ ";\n"
+ " public static final String LIBRARY_PACKAGE_NAME = "
+ "\"$package_name\"".replace("$package_name", packageName)
+ ";\n"
+ " public static final String BUILD_TYPE = "
+ "\"release\""
+ ";\n"
+ "}\n";
FileUtils.writeStringToFile(buildConfigClass, buildConfigString, Charset.defaultCharset());
}
private String getApplicationId() throws IOException {
String packageName = getModule().getNameSpace();
String content = parseString(getModule().getGradleFile());
if (content != null) {
boolean isAndroidLibrary = false;
if (content.contains("com.android.library")) {
isAndroidLibrary = true;
}
if (isAndroidLibrary) {
return packageName;
} else {
if (content.contains("namespace") && !content.contains("applicationId")) {
throw new IOException(
"Unable to find applicationId in "
+ getModule().getRootFile().getName()
+ "/build.gradle file");
} else if (content.contains("applicationId") && content.contains("namespace")) {
return packageName;
} else if (content.contains("applicationId") && !content.contains("namespace")) {
packageName = getModule().getApplicationId();
} else {
throw new IOException(
"Unable to find namespace or applicationId in "
+ getModule().getRootFile().getName()
+ "/build.gradle file");
}
}
} else {
throw new IOException(
"Unable to read " + getModule().getRootFile().getName() + "/build.gradle file");
}
return packageName;
}
private String parseString(File gradle) {
if (gradle != null && gradle.exists()) {
try {
String readString = FileUtils.readFileToString(gradle, Charset.defaultCharset());
if (readString != null && !readString.isEmpty()) {
return readString;
}
} catch (IOException e) {
// handle the exception here, if needed
}
}
return null;
}
}
| 7,539 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
GenerateDebugBuildConfigTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/buildconfig/GenerateDebugBuildConfigTask.java | package com.tyron.builder.compiler.buildconfig;
import android.util.Log;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
public class GenerateDebugBuildConfigTask extends Task<AndroidModule> {
private static final String TAG = "generateDebugBuildConfig";
public GenerateDebugBuildConfigTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
getModule().getJavaFiles();
getModule().getKotlinFiles();
}
@Override
public void run() throws IOException, CompilationFailedException {
GenerateBuildConfig();
}
private void GenerateBuildConfig() throws IOException {
Log.d(TAG, "Generating BuildConfig.java");
String packageName = getApplicationId();
File packageDir =
new File(getModule().getBuildDirectory() + "/gen", packageName.replace('.', '/'));
File buildConfigClass = new File(packageDir, "/BuildConfig.java");
if (packageDir.exists()) {
} else {
packageDir.mkdirs();
}
File parentDir = buildConfigClass.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
if (!buildConfigClass.exists() && !buildConfigClass.createNewFile()) {
throw new IOException("Unable to generate BuildConfig.java");
}
String content = parseString(getModule().getGradleFile());
if (content != null) {
boolean isAndroidLibrary = false;
if (content.contains("com.android.library")) {
isAndroidLibrary = true;
}
if (!isAndroidLibrary) {
String buildConfigString =
"/**"
+ "\n"
+ "* Automatically generated file. DO NOT MODIFY"
+ "\n"
+ "*/"
+ "\n"
+ "package "
+ packageName
+ ";\n"
+ "\n"
+ "public final class BuildConfig {"
+ "\n"
+ " public static final boolean DEBUG = "
+ "Boolean.parseBoolean(\"true\")"
+ ";\n"
+ " public static final String APPLICATION_ID = "
+ "\"$package_name\"".replace("$package_name", packageName)
+ ";\n"
+ " public static final String BUILD_TYPE = "
+ "\"debug\""
+ ";\n"
+ " public static final int VERSION_CODE = "
+ getModule().getVersionCode()
+ ";\n"
+ " public static final String VERSION_NAME = "
+ "\"$version_name\"".replace("$version_name", getModule().getVersionName())
+ ";\n"
+ "}\n";
FileUtils.writeStringToFile(buildConfigClass, buildConfigString, Charset.defaultCharset());
} else {
String buildConfigString =
"/**"
+ "\n"
+ "* Automatically generated file. DO NOT MODIFY"
+ "\n"
+ "*/"
+ "\n"
+ "package "
+ packageName
+ ";\n"
+ "\n"
+ "public final class BuildConfig {"
+ "\n"
+ " public static final boolean DEBUG = "
+ "Boolean.parseBoolean(\"true\")"
+ ";\n"
+ " public static final String LIBRARY_PACKAGE_NAME = "
+ "\"$package_name\"".replace("$package_name", packageName)
+ ";\n"
+ " public static final String BUILD_TYPE = "
+ "\"debug\""
+ ";\n"
+ "}\n";
FileUtils.writeStringToFile(buildConfigClass, buildConfigString, Charset.defaultCharset());
}
}
}
public void GenerateBuildConfig(String packageName, File genDir) throws IOException {
Log.d(TAG, "Generating BuildConfig.java");
if (packageName == null) {
throw new IOException("Unable to find namespace in build.gradle file");
}
File dir = new File(genDir, packageName.replace('.', '/'));
File buildConfigClass = new File(dir, "/BuildConfig.java");
if (genDir.exists() || dir.exists()) {
} else {
genDir.mkdirs();
dir.mkdirs();
}
File parentDir = buildConfigClass.getParentFile();
if (!parentDir.exists()) {
parentDir.mkdirs();
}
if (!buildConfigClass.exists() && !buildConfigClass.createNewFile()) {
throw new IOException("Unable to generate BuildConfig.java");
}
String buildConfigString =
"/**"
+ "\n"
+ "* Automatically generated file. DO NOT MODIFY"
+ "\n"
+ "*/"
+ "\n"
+ "package "
+ packageName
+ ";\n"
+ "\n"
+ "public final class BuildConfig {"
+ "\n"
+ " public static final boolean DEBUG = "
+ "Boolean.parseBoolean(\"true\")"
+ ";\n"
+ " public static final String LIBRARY_PACKAGE_NAME = "
+ "\"$package_name\"".replace("$package_name", packageName)
+ ";\n"
+ " public static final String BUILD_TYPE = "
+ "\"debug\""
+ ";\n"
+ "}\n";
FileUtils.writeStringToFile(buildConfigClass, buildConfigString, Charset.defaultCharset());
}
private String getApplicationId() throws IOException {
String packageName = getModule().getNameSpace();
String content = parseString(getModule().getGradleFile());
if (content != null) {
boolean isAndroidLibrary = false;
if (content.contains("com.android.library")) {
isAndroidLibrary = true;
}
if (isAndroidLibrary) {
return packageName;
} else {
if (content.contains("namespace") && !content.contains("applicationId")) {
throw new IOException(
"Unable to find applicationId in "
+ getModule().getRootFile().getName()
+ "/build.gradle file");
} else if (content.contains("applicationId") && content.contains("namespace")) {
return packageName;
} else if (content.contains("applicationId") && !content.contains("namespace")) {
packageName = getModule().getApplicationId();
} else {
throw new IOException(
"Unable to find namespace or applicationId in "
+ getModule().getRootFile().getName()
+ "/build.gradle file");
}
}
} else {
throw new IOException(
"Unable to read " + getModule().getRootFile().getName() + "/build.gradle file");
}
return packageName;
}
private String parseString(File gradle) {
if (gradle != null && gradle.exists()) {
try {
String readString = FileUtils.readFileToString(gradle, Charset.defaultCharset());
if (readString != null && !readString.isEmpty()) {
return readString;
}
} catch (IOException e) {
// handle the exception here, if needed
}
}
return null;
}
}
| 7,603 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ManifestMergeTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/manifest/ManifestMergeTask.java | package com.tyron.builder.compiler.manifest;
import com.tyron.builder.BuildModule;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.compiler.manifest.ManifestMerger2.SystemProperty;
import com.tyron.builder.compiler.manifest.xml.XmlFormatPreferences;
import com.tyron.builder.compiler.manifest.xml.XmlFormatStyle;
import com.tyron.builder.compiler.manifest.xml.XmlPrettyPrinter;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class ManifestMergeTask extends Task<AndroidModule> {
private File mOutputFile;
private File mMainManifest;
private File[] mLibraryManifestFiles;
private String mPackageName;
public ManifestMergeTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return "mergeManifest";
}
@Override
public void prepare(BuildType type) throws IOException {
mPackageName = getApplicationId();
mOutputFile = new File(getModule().getBuildDirectory(), "bin");
if (!mOutputFile.exists()) {
if (!mOutputFile.mkdirs()) {
throw new IOException("Unable to create build directory");
}
}
mOutputFile = new File(mOutputFile, "AndroidManifest.xml");
if (!mOutputFile.exists()) {
if (!mOutputFile.createNewFile()) {
throw new IOException("Unable to create manifest file");
}
}
mMainManifest = getModule().getManifestFile();
if (!mMainManifest.exists()) {
throw new IOException("Unable to find the main manifest file");
}
File tempDir = new File(getModule().getBuildDirectory(), "bin/temp");
if (!tempDir.exists()) {
tempDir.mkdirs();
}
File tempManifest = new File(tempDir, "AndroidManifest.xml");
if (tempManifest.exists()) {
tempManifest.delete();
}
if (!tempManifest.exists()) {
if (!tempManifest.createNewFile()) {
throw new IOException("Unable to create temp manifest file");
}
}
try {
String content = new String(Files.readAllBytes(Paths.get(mMainManifest.getAbsolutePath())));
FileUtils.writeStringToFile(tempManifest, content, Charset.defaultCharset());
addPackageName(tempManifest, mPackageName);
mMainManifest = tempManifest;
} catch (Exception e) {
mMainManifest = getModule().getManifestFile();
tempDir = new File(BuildModule.getContext().getExternalFilesDir(null), "/temp");
if (!tempDir.exists()) {
tempDir.mkdirs();
}
tempManifest = new File(tempDir, "AndroidManifest.xml");
if (tempManifest.exists()) {
tempManifest.delete();
}
if (!tempManifest.exists()) {
if (!tempManifest.createNewFile()) {
throw new IOException("Unable to create temp manifest file");
}
}
try {
String content = new String(Files.readAllBytes(Paths.get(mMainManifest.getAbsolutePath())));
FileUtils.writeStringToFile(tempManifest, content, Charset.defaultCharset());
addPackageName(tempManifest, mPackageName);
mMainManifest = tempManifest;
} catch (Exception ex) {
mMainManifest = getModule().getManifestFile();
}
}
List<File> manifests = new ArrayList<>();
List<File> libraries = getModule().getLibraries();
// Filter the libraries and add all that has a AndroidManifest.xml file
for (File library : libraries) {
File parent = library.getParentFile();
if (parent == null) {
getLogger().warning("Unable to access parent directory of a library");
continue;
}
File manifest = new File(parent, "AndroidManifest.xml");
if (manifest.exists()) {
if (manifest.length() != 0) {
manifests.add(manifest);
}
}
}
mLibraryManifestFiles = manifests.toArray(new File[0]);
}
@Override
public void run() throws IOException, CompilationFailedException {
ManifestMerger2.Invoker<?> invoker =
ManifestMerger2.newMerger(
mMainManifest, getLogger(), ManifestMerger2.MergeType.APPLICATION);
invoker.setOverride(SystemProperty.PACKAGE, mPackageName);
invoker.setOverride(SystemProperty.MIN_SDK_VERSION, String.valueOf(getModule().getMinSdk()));
invoker.setOverride(
SystemProperty.TARGET_SDK_VERSION, String.valueOf(getModule().getTargetSdk()));
invoker.setOverride(SystemProperty.VERSION_CODE, String.valueOf(getModule().getVersionCode()));
invoker.setOverride(SystemProperty.VERSION_NAME, getModule().getVersionName());
if (mLibraryManifestFiles != null) {
invoker.addLibraryManifests(mLibraryManifestFiles);
}
invoker.setVerbose(false);
try {
MergingReport report = invoker.merge();
if (report.getResult().isError()) {
report.log(getLogger());
throw new CompilationFailedException(report.getReportString());
}
if (report.getMergedDocument().isPresent()) {
Document document = report.getMergedDocument().get().getXml();
// inject the tools namespace, some libraries may use the tools attribute but
// the main manifest may not have it defined
document
.getDocumentElement()
.setAttribute(
SdkConstants.XMLNS_PREFIX + SdkConstants.TOOLS_PREFIX, SdkConstants.TOOLS_URI);
String contents =
XmlPrettyPrinter.prettyPrint(
document,
XmlFormatPreferences.defaults(),
XmlFormatStyle.get(document),
null,
false);
FileUtils.writeStringToFile(mOutputFile, contents, Charset.defaultCharset());
}
} catch (ManifestMerger2.MergeFailureException e) {
throw new CompilationFailedException(e);
}
}
public void merge(File root, File gradle) throws IOException, CompilationFailedException {
getLogger().debug("> Task :" + root.getName() + ":" + "mergeManifest");
String namespace = namespace(root.getName(), gradle);
File outputFile = new File(root, "build/bin/AndroidManifest.xml");
File mainManifest = new File(root, "src/main/AndroidManifest.xml");
File tempDir = new File(root, "build/bin/temp");
if (!tempDir.exists()) {
tempDir.mkdirs();
}
File tempManifest = new File(tempDir, "AndroidManifest.xml");
if (tempManifest.exists()) {
tempManifest.delete();
}
if (!tempManifest.exists()) {
if (!tempManifest.createNewFile()) {
throw new IOException("Unable to create temp manifest file");
}
}
try {
String content = new String(Files.readAllBytes(Paths.get(mainManifest.getAbsolutePath())));
FileUtils.writeStringToFile(tempManifest, content, Charset.defaultCharset());
addPackageName(tempManifest, namespace);
mMainManifest = tempManifest;
} catch (Exception e) {
mMainManifest = new File(root, "src/main/AndroidManifest.xml");
tempDir = new File(BuildModule.getContext().getExternalFilesDir(null), "/temp");
if (!tempDir.exists()) {
tempDir.mkdirs();
}
tempManifest = new File(tempDir, "AndroidManifest.xml");
if (tempManifest.exists()) {
tempManifest.delete();
}
if (!tempManifest.exists()) {
if (!tempManifest.createNewFile()) {
throw new IOException("Unable to create temp manifest file");
}
}
try {
String content = new String(Files.readAllBytes(Paths.get(mMainManifest.getAbsolutePath())));
FileUtils.writeStringToFile(tempManifest, content, Charset.defaultCharset());
addPackageName(tempManifest, mPackageName);
mMainManifest = tempManifest;
} catch (Exception ex) {
mMainManifest = getModule().getManifestFile();
}
}
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
if (!mainManifest.getParentFile().exists()) {
throw new IOException("Unable to find the main manifest file");
}
int minSdk = getModule().getMinSdk(gradle);
int targetSdk = getModule().getTargetSdk(gradle);
int versionCode = getModule().getVersionCode(gradle);
String versionName = getModule().getVersionName(gradle);
merge(mainManifest, namespace, minSdk, targetSdk, versionCode, versionName, outputFile);
}
public void merge(
File mainManifest,
String namespace,
int minSdk,
int targetSdk,
int versionCode,
String versionName,
File outputFile)
throws IOException, CompilationFailedException {
ManifestMerger2.Invoker<?> invoker =
ManifestMerger2.newMerger(mainManifest, getLogger(), ManifestMerger2.MergeType.LIBRARY);
invoker.setOverride(SystemProperty.PACKAGE, namespace);
invoker.setOverride(SystemProperty.MIN_SDK_VERSION, String.valueOf(minSdk));
invoker.setOverride(SystemProperty.TARGET_SDK_VERSION, String.valueOf(targetSdk));
invoker.setOverride(SystemProperty.VERSION_CODE, String.valueOf(versionCode));
invoker.setOverride(SystemProperty.VERSION_NAME, versionName);
invoker.setVerbose(false);
try {
MergingReport report = invoker.merge();
if (report.getResult().isError()) {
report.log(getLogger());
throw new CompilationFailedException(report.getReportString());
}
if (report.getMergedDocument().isPresent()) {
Document document = report.getMergedDocument().get().getXml();
// inject the tools namespace, some libraries may use the tools attribute but
// the main manifest may not have it defined
String contents =
XmlPrettyPrinter.prettyPrint(
document,
XmlFormatPreferences.defaults(),
XmlFormatStyle.get(document),
null,
false);
FileUtils.writeStringToFile(outputFile, contents, Charset.defaultCharset());
}
} catch (ManifestMerger2.MergeFailureException e) {
throw new CompilationFailedException(e);
}
}
private String getApplicationId() throws IOException {
String packageName = getModule().getNameSpace();
String content = parseString(getModule().getGradleFile());
if (content != null) {
boolean isAndroidLibrary = false;
if (content.contains("com.android.library")) {
isAndroidLibrary = true;
}
if (isAndroidLibrary) {
return packageName;
} else {
if (content.contains("namespace") && !content.contains("applicationId")) {
throw new IOException(
"Unable to find applicationId in "
+ getModule().getRootFile().getName()
+ "/build.gradle file");
} else if (content.contains("applicationId") && content.contains("namespace")) {
return packageName;
} else if (content.contains("applicationId") && !content.contains("namespace")) {
packageName = getModule().getApplicationId();
} else {
throw new IOException(
"Unable to find namespace or applicationId in "
+ getModule().getRootFile().getName()
+ "/build.gradle file");
}
}
} else {
throw new IOException(
"Unable to read " + getModule().getRootFile().getName() + "/build.gradle file");
}
return packageName;
}
private String parseString(File gradle) {
if (gradle != null && gradle.exists()) {
try {
String readString = FileUtils.readFileToString(gradle, Charset.defaultCharset());
if (readString != null && !readString.isEmpty()) {
return readString;
}
} catch (IOException e) {
// handle the exception here, if needed
}
}
return null;
}
private String namespace(String root, File gradle) throws IOException {
String packageName = getModule().getNameSpace(gradle);
String content = parseString(gradle);
if (content != null) {
if (!content.contains("namespace")) {
throw new IOException("Unable to find namespace in " + root + "/build.gradle file");
}
} else {
throw new IOException("Unable to read " + root + "/build.gradle file");
}
return packageName;
}
public void addPackageName(File mMainManifest, String packageName)
throws ParserConfigurationException, IOException, SAXException, TransformerException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(mMainManifest);
doc.getDocumentElement().normalize();
Element root = doc.getDocumentElement();
if (!root.hasAttribute("package")) {
root.setAttribute("package", packageName);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(mMainManifest);
transformer.transform(source, result);
} else {
root.setAttribute("package", packageName);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(mMainManifest);
transformer.transform(source, result);
}
}
} | 14,331 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
R8Task.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/dex/R8Task.java | package com.tyron.builder.compiler.dex;
import com.android.tools.r8.CompilationMode;
import com.android.tools.r8.OutputMode;
import com.android.tools.r8.R8;
import com.android.tools.r8.R8Command;
import com.android.tools.r8.origin.Origin;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class R8Task extends Task<AndroidModule> {
private static final String TAG = "mergeDexWithR8";
public R8Task(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {}
@Override
public void run() throws IOException, CompilationFailedException {
try {
File output = new File(getModule().getBuildDirectory(), "bin");
File mappingOutput = new File(output, "proguard-mapping.txt");
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
R8Command.Builder command =
R8Command.builder(new DexDiagnosticHandler(getLogger(), getModule()))
.addProgramFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.addLibraryFiles(getLibraryFiles())
.addProgramFiles(
D8Task.getClassFiles(
new File(getModule().getBuildDirectory(), "bin/kotlin/classes")))
.addProgramFiles(
D8Task.getClassFiles(
new File(getModule().getBuildDirectory(), "bin/java/classes")))
.addProguardConfiguration(getDefaultProguardRule(), Origin.unknown())
.addProguardConfigurationFiles(getProguardRules())
.setMinApiLevel(getModule().getMinSdk())
.setMode(CompilationMode.RELEASE)
.setProguardMapOutputPath(mappingOutput.toPath())
.setOutput(output.toPath(), OutputMode.DexIndexed);
R8.run(command.build());
} catch (com.android.tools.r8.CompilationFailedException e) {
throw new CompilationFailedException(e);
}
}
private List<String> getDefaultProguardRule() {
List<String> rules = new ArrayList<>();
// Keep resource classes
rules.addAll(
createConfiguration(
"-keepclassmembers class **.R$* {\n" + " public static <fields>;\n" + "}"));
rules.addAll(
createConfiguration(
"-keepclassmembers class *"
+ " implements android.os.Parcelable {\n"
+ " public static final android.os.Parcelable$Creator CREATOR;\n"
+ "}"));
// For native methods, see http://proguard.sourceforge.net/manual/examples.html#native
rules.addAll(
createConfiguration(
"-keepclasseswithmembernames class * {\n" + " native <methods>;\n" + "}"));
rules.addAll(
createConfiguration(
"-keepclassmembers enum * {\n"
+ " public static **[] values();\n"
+ " public static ** valueOf(java.lang.String);\n"
+ "}"));
return rules;
}
private List<String> createConfiguration(String string) {
return Arrays.asList(string.split("\n"));
}
private Collection<Path> getJarFiles() {
Collection<Path> paths = new ArrayList<>();
for (File it : getModule().getLibraries()) {
paths.add(it.toPath());
}
return paths;
}
private List<Path> getProguardRules() {
List<Path> rules = new ArrayList<>();
getModule()
.getLibraries()
.forEach(
it -> {
File parent = it.getParentFile();
if (parent != null) {
File proguardFile = new File(parent, "proguard.txt");
if (proguardFile.exists()) {
rules.add(proguardFile.toPath());
}
}
});
File proguardRuleTxt = new File(getModule().getRootFile(), "proguard-rules.pro");
if (proguardRuleTxt.exists()) {
rules.add(proguardRuleTxt.toPath());
}
File aapt2Rules = new File(getModule().getBuildDirectory(), "bin/res/generated-rules.txt");
if (aapt2Rules.exists()) {
rules.add(aapt2Rules.toPath());
}
return rules;
}
private List<Path> getLibraryFiles() {
List<Path> path = new ArrayList<>();
path.add(getModule().getBootstrapJarFile().toPath());
path.add(getModule().getLambdaStubsJarFile().toPath());
return path;
}
}
| 5,455 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaD8Task.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/dex/JavaD8Task.java | package com.tyron.builder.compiler.dex;
import androidx.annotation.VisibleForTesting;
import com.android.tools.r8.CompilationMode;
import com.android.tools.r8.D8;
import com.android.tools.r8.D8Command;
import com.android.tools.r8.DiagnosticsHandler;
import com.android.tools.r8.OutputMode;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.compiler.incremental.dex.IncrementalD8Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.common.util.Cache;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
/**
* Task for dexing a {@link JavaModule} this is copied from {@link IncrementalD8Task} but with the
* minimum API levels hardcoded to 21
*/
public class JavaD8Task extends Task<JavaModule> {
public JavaD8Task(Project project, JavaModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return "JavaD8Task";
}
private DiagnosticsHandler diagnosticsHandler;
private List<Path> mClassFiles;
private List<Path> mFilesToCompile;
private Cache<String, List<File>> mDexCache;
private Path mOutputPath;
private BuildType mBuildType;
@Override
public void prepare(BuildType type) throws IOException {
mBuildType = type;
diagnosticsHandler = new DexDiagnosticHandler(getLogger(), getModule());
mDexCache = getModule().getCache(IncrementalD8Task.CACHE_KEY, new Cache<>());
File output = new File(getModule().getBuildDirectory(), "intermediate/classes");
if (!output.exists() && !output.mkdirs()) {
throw new IOException("Unable to create output directory");
}
mOutputPath = output.toPath();
mFilesToCompile = new ArrayList<>();
mClassFiles =
new ArrayList<>(
D8Task.getClassFiles(new File(getModule().getBuildDirectory(), "bin/java/classes")));
mClassFiles.addAll(
D8Task.getClassFiles(new File(getModule().getBuildDirectory(), "bin/kotlin/classes")));
for (Cache.Key<String> key : new HashSet<>(mDexCache.getKeys())) {
if (!mFilesToCompile.contains(key.file)) {
File file = mDexCache.get(key.file, "dex").iterator().next();
deleteAllFiles(file, ".dex");
mDexCache.remove(key.file, "dex");
}
}
for (Path file : mClassFiles) {
if (mDexCache.needs(file, "dex")) {
mFilesToCompile.add(file);
}
}
}
@Override
public void run() throws IOException, CompilationFailedException {
if (mBuildType == BuildType.RELEASE || mBuildType == BuildType.AAB) {
doRelease();
} else if (mBuildType == BuildType.DEBUG) {
doDebug();
}
}
@Override
protected void clean() {
super.clean();
}
private void doRelease() throws CompilationFailedException {
try {
ensureDexedLibraries();
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
D8Command command =
D8Command.builder(diagnosticsHandler)
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.addProgramFiles(mFilesToCompile)
.addLibraryFiles(getLibraryFiles())
.setMinApiLevel(getModule().getMinSdk())
.setMode(CompilationMode.RELEASE)
.setIntermediate(true)
.setOutput(mOutputPath, OutputMode.DexFilePerClassFile)
.build();
D8.run(command);
for (Path file : mFilesToCompile) {
mDexCache.load(file, "dex", Collections.singletonList(getDexFile(file.toFile())));
}
mergeRelease();
} catch (com.android.tools.r8.CompilationFailedException e) {
throw new CompilationFailedException(e);
}
}
private void doDebug() throws CompilationFailedException {
try {
ensureDexedLibraries();
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
D8Command command =
D8Command.builder(diagnosticsHandler)
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.addProgramFiles(mFilesToCompile)
.addLibraryFiles(getLibraryFiles())
.setMinApiLevel(getModule().getMinSdk())
.setMode(CompilationMode.DEBUG)
.setIntermediate(true)
.setOutput(mOutputPath, OutputMode.DexFilePerClassFile)
.build();
D8.run(command);
for (Path file : mFilesToCompile) {
mDexCache.load(file, "dex", Collections.singletonList(getDexFile(file.toFile())));
}
D8Command.Builder builder =
D8Command.builder(diagnosticsHandler)
.addProgramFiles(getAllDexFiles(mOutputPath.toFile()))
.addLibraryFiles(getLibraryFiles())
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.setMinApiLevel(getModule().getMinSdk());
File output = new File(getModule().getBuildDirectory(), "bin");
builder.setMode(CompilationMode.DEBUG);
builder.setOutput(output.toPath(), OutputMode.DexIndexed);
D8.run(builder.build());
} catch (com.android.tools.r8.CompilationFailedException e) {
throw new CompilationFailedException(e);
}
}
private void mergeRelease() throws com.android.tools.r8.CompilationFailedException {
getLogger().debug("Merging dex files using R8");
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
File output = new File(getModule().getBuildDirectory(), "bin");
D8Command command =
D8Command.builder(diagnosticsHandler)
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.addLibraryFiles(getLibraryFiles())
.addProgramFiles(getAllDexFiles(mOutputPath.toFile()))
.addProgramFiles(getLibraryDexes())
.setMinApiLevel(getModule().getMinSdk())
.setMode(CompilationMode.RELEASE)
.setOutput(output.toPath(), OutputMode.DexIndexed)
.build();
D8.run(command);
}
@VisibleForTesting
public List<Path> getCompiledFiles() {
return mFilesToCompile;
}
private List<Path> getLibraryDexes() {
List<Path> dexes = new ArrayList<>();
for (File file : getModule().getLibraries()) {
File parent = file.getParentFile();
if (parent != null) {
File[] dexFiles = parent.listFiles(file1 -> file1.getName().endsWith(".dex"));
if (dexFiles != null) {
dexes.addAll(Arrays.stream(dexFiles).map(File::toPath).collect(Collectors.toList()));
}
}
}
return dexes;
}
private File getDexFile(File file) {
File output = new File(getModule().getBuildDirectory(), "bin/classes/");
String packageName =
file.getAbsolutePath()
.replace(output.getAbsolutePath(), "")
.substring(1)
.replace(".class", ".dex");
File intermediate = new File(getModule().getBuildDirectory(), "intermediate/classes");
File file1 = new File(intermediate, packageName);
return file1;
}
/**
* Ensures that all libraries of the project has been dex-ed
*
* @throws com.android.tools.r8.CompilationFailedException if the compilation has failed
*/
protected void ensureDexedLibraries() throws com.android.tools.r8.CompilationFailedException {
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
for (File lib : uniqueLibraryFiles) {
File parentFile = lib.getParentFile();
if (parentFile == null) {
continue;
}
File[] libFiles = lib.getParentFile().listFiles();
if (libFiles == null) {
if (!lib.delete()) {
getLogger().warning("Failed to delete " + lib.getAbsolutePath());
}
} else {
File dex = new File(lib.getParentFile(), "classes.dex");
if (dex.exists()) {
continue;
}
if (lib.exists()) {
getLogger().debug("Dexing jar " + parentFile.getName());
D8Command command =
D8Command.builder(diagnosticsHandler)
.addLibraryFiles(getLibraryFiles())
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.setMinApiLevel(getModule().getMinSdk())
.addProgramFiles(lib.toPath())
.setMode(CompilationMode.RELEASE)
.setOutput(lib.getParentFile().toPath(), OutputMode.DexIndexed)
.build();
D8.run(command);
}
}
}
}
private List<Path> getLibraryFiles() {
List<Path> path = new ArrayList<>();
path.add(getModule().getLambdaStubsJarFile().toPath());
path.add(getModule().getBootstrapJarFile().toPath());
return path;
}
private void deleteAllFiles(File classFile, String ext) throws IOException {
File dexFile = getDexFile(classFile);
if (!dexFile.exists()) {
return;
}
File parent = dexFile.getParentFile();
String name = dexFile.getName().replace(ext, "");
if (parent != null) {
File[] children =
parent.listFiles((c) -> c.getName().endsWith(ext) && c.getName().contains("$"));
if (children != null) {
for (File child : children) {
if (child.getName().startsWith(name)) {
FileUtils.delete(child);
}
}
}
}
FileUtils.delete(dexFile);
}
private List<Path> getAllDexFiles(File dir) {
List<Path> files = new ArrayList<>();
File[] children = dir.listFiles(c -> c.getName().endsWith(".dex") || c.isDirectory());
if (children != null) {
for (File child : children) {
if (child.isDirectory()) {
files.addAll(getAllDexFiles(child));
} else {
files.add(child.toPath());
}
}
}
return files;
}
}
| 12,283 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
D8Task.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/dex/D8Task.java | package com.tyron.builder.compiler.dex;
import com.android.tools.r8.CompilationMode;
import com.android.tools.r8.D8;
import com.android.tools.r8.D8Command;
import com.android.tools.r8.OutputMode;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.builder.project.api.JavaModule;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/** Converts class files into dex files and merges them in the process */
@SuppressWarnings("NewApi")
public class D8Task extends Task<JavaModule> {
private static final String TAG = D8Task.class.getSimpleName();
public D8Task(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {}
@Override
public void run() throws IOException, CompilationFailedException {
compile();
}
public void compile() throws CompilationFailedException {
try {
getLogger().debug("Dexing libraries.");
ensureDexedLibraries();
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
getLogger().debug("Merging dexes and source files");
List<Path> libraryDexes = getLibraryDexes();
D8Command command =
D8Command.builder(new DexDiagnosticHandler(getLogger(), getModule()))
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.setMinApiLevel(getModule().getMinSdk())
.addLibraryFiles(getLibraryFiles())
.addProgramFiles(
getClassFiles(new File(getModule().getBuildDirectory(), "bin/classes")))
.addProgramFiles(libraryDexes)
.setOutput(
new File(getModule().getBuildDirectory(), "bin").toPath(), OutputMode.DexIndexed)
.build();
D8.run(command);
} catch (com.android.tools.r8.CompilationFailedException e) {
throw new CompilationFailedException(e);
}
}
/**
* Ensures that all libraries of the project has been dex-ed
*
* @throws com.android.tools.r8.CompilationFailedException if the compilation has failed
*/
protected void ensureDexedLibraries() throws com.android.tools.r8.CompilationFailedException {
List<File> libraries = getModule().getLibraries();
Map<Long, File> fileSizeMap = new HashMap<>();
// Calculate file sizes and store them in a map
for (File file : libraries) {
try {
long fileSize = Files.size(file.toPath());
fileSizeMap.put(fileSize, file);
} catch (IOException e) {
e.printStackTrace();
}
}
// Remove duplicates based on file size
List<File> uniqueLibraryFiles = fileSizeMap.values().stream().collect(Collectors.toList());
for (File lib : uniqueLibraryFiles) {
File parentFile = lib.getParentFile();
if (parentFile == null) {
continue;
}
File[] libFiles = lib.getParentFile().listFiles();
if (libFiles == null) {
if (!lib.delete()) {
getLogger().warning("Failed to delete " + lib.getAbsolutePath());
}
} else {
File dex = new File(lib.getParentFile(), "classes.dex");
if (dex.exists()) {
continue;
}
if (lib.exists()) {
getLogger().debug("Dexing jar " + parentFile.getName());
D8Command command =
D8Command.builder(new DexDiagnosticHandler(getLogger(), getModule()))
.addLibraryFiles(getLibraryFiles())
.addClasspathFiles(
uniqueLibraryFiles.stream().map(File::toPath).collect(Collectors.toList()))
.setMinApiLevel(getModule().getMinSdk())
.addProgramFiles(lib.toPath())
.setMode(CompilationMode.RELEASE)
.setOutput(lib.getParentFile().toPath(), OutputMode.DexIndexed)
.build();
D8.run(command);
}
}
}
}
private List<Path> getLibraryFiles() {
List<Path> path = new ArrayList<>();
path.add(getModule().getBootstrapJarFile().toPath());
path.add(getModule().getLambdaStubsJarFile().toPath());
return path;
}
/**
* Retrieves a list of all libraries dexes including the extra dex files if it has one
*
* @return list of all dex files
*/
private List<Path> getLibraryDexes() {
List<Path> dexes = new ArrayList<>();
for (File file : getModule().getLibraries()) {
File parent = file.getParentFile();
if (parent != null) {
File[] dexFiles = parent.listFiles(file1 -> file1.getName().endsWith(".dex"));
if (dexFiles != null) {
dexes.addAll(Arrays.stream(dexFiles).map(File::toPath).collect(Collectors.toList()));
}
}
}
return dexes;
}
public static List<Path> getClassFiles(File root) {
List<Path> paths = new ArrayList<>();
File[] files = root.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
paths.addAll(getClassFiles(file));
} else {
if (file.getName().endsWith(".class")) {
paths.add(file.toPath());
}
}
}
}
return paths;
}
}
| 6,218 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
DexDiagnosticHandler.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/dex/DexDiagnosticHandler.java | package com.tyron.builder.compiler.dex;
import android.util.Log;
import com.android.tools.r8.Diagnostic;
import com.android.tools.r8.DiagnosticsHandler;
import com.android.tools.r8.DiagnosticsLevel;
import com.android.tools.r8.errors.DuplicateTypesDiagnostic;
import com.android.tools.r8.origin.Origin;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.model.DiagnosticWrapper;
import com.tyron.builder.model.Library;
import com.tyron.builder.project.api.JavaModule;
import java.io.File;
import java.util.Collection;
public class DexDiagnosticHandler implements DiagnosticsHandler {
private static final String METAINF_ERROR = "Resource 'META-INF/MANIFEST.MF' already exists.";
private static final String LIBRARY_DIR = "build/libs/";
private static final String CLASSES_DIR = "build/intermediate/classes/";
private final ILogger mLogger;
private final JavaModule mModule;
public DexDiagnosticHandler(ILogger logger, JavaModule module) {
mLogger = logger;
mModule = module;
}
@Override
public void error(Diagnostic diagnostic) {
mLogger.error(wrap(diagnostic, DiagnosticsLevel.ERROR));
}
@Override
public void warning(Diagnostic diagnostic) {
mLogger.warning(wrap(diagnostic, DiagnosticsLevel.WARNING));
}
@Override
public void info(Diagnostic diagnostic) {
mLogger.info(wrap(diagnostic, DiagnosticsLevel.INFO));
}
@Override
public DiagnosticsLevel modifyDiagnosticsLevel(
DiagnosticsLevel diagnosticsLevel, Diagnostic diagnostic) {
if (diagnostic.getDiagnosticMessage().equals(METAINF_ERROR)) {
return DiagnosticsLevel.WARNING;
}
Log.d("DiagnosticHandler", diagnostic.getDiagnosticMessage());
return diagnosticsLevel;
}
private DiagnosticWrapper wrap(Diagnostic diagnostic, DiagnosticsLevel level) {
DiagnosticWrapper wrapper = new DiagnosticWrapper();
if (diagnostic instanceof DuplicateTypesDiagnostic) {
DuplicateTypesDiagnostic d = (DuplicateTypesDiagnostic) diagnostic;
String typeName = d.getType().getTypeName();
String message =
""
+ "The type "
+ typeName
+ " is defined multiple times in multiple jars. "
+ "There can only be one class with the same package and name. Please locate the "
+ "following jars and determine which class is appropriate to keep. \n\n";
message += "Files: \n";
message += printDuplicateOrigins(d.getOrigins());
wrapper.setMessage(message);
} else {
wrapper.setMessage(diagnostic.getDiagnosticMessage());
}
switch (level) {
case WARNING:
wrapper.setKind(javax.tools.Diagnostic.Kind.WARNING);
break;
case ERROR:
wrapper.setKind(javax.tools.Diagnostic.Kind.ERROR);
break;
case INFO:
wrapper.setKind(javax.tools.Diagnostic.Kind.NOTE);
break;
}
return wrapper;
}
private String printDuplicateOrigins(Collection<Origin> origins) {
StringBuilder builder = new StringBuilder();
for (Origin origin : origins) {
builder.append("\n");
if (isClassFile(origin)) {
builder.append("Class/Source file");
builder.append("\n");
builder.append("path: ");
builder.append(getClassFile(origin));
} else if (isJarFile(origin)) {
builder.append("Jar file");
builder.append("\n");
builder.append("path: ");
builder.append(getLibraryFile(origin));
} else {
builder.append("path: ");
builder.append(origin.part());
}
builder.append("\n");
}
return builder.toString();
}
private boolean isJarFile(Origin origin) {
return origin.part().contains(LIBRARY_DIR);
}
private String getLibraryFile(Origin origin) {
String part = origin.part();
File file = new File(part);
if (!file.exists()) {
return part;
}
File parent = file.getParentFile();
if (parent == null) {
return part;
}
String hash = parent.getName();
Library library = mModule.getLibrary(hash);
if (library == null) {
return part;
}
if (library.isDependency()) {
return library.getDeclaration();
}
return library.getSourceFile().getAbsolutePath();
}
private boolean isClassFile(Origin origin) {
return origin.part().contains(CLASSES_DIR);
}
private String getClassFile(Origin origin) {
String part = origin.part();
int index = part.indexOf(CLASSES_DIR);
if (index == -1) {
return part;
}
int endIndex = part.length();
if (part.endsWith(".dex")) {
endIndex -= ".dex".length();
}
index += CLASSES_DIR.length();
String fqn = part.substring(index, endIndex).replace('/', '.');
File javaFile = mModule.getJavaFile(fqn);
if (javaFile == null) {
return part;
}
return javaFile.getAbsolutePath();
}
}
| 4,911 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
BuildAarTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/aar/BuildAarTask.java | package com.tyron.builder.compiler.aar;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.internal.jar.AssembleJar;
import com.tyron.builder.internal.jar.JarOptionsImpl;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Attributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.FileUtils;
public class BuildAarTask extends Task<JavaModule> {
private static final String TAG = "assembleAar";
public BuildAarTask(Project project, JavaModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {}
@Override
public void run() throws IOException, CompilationFailedException {
File javaClasses = new File(getModule().getRootFile(), "build/bin/java/classes");
File kotlinClasses = new File(getModule().getRootFile(), "build/bin/kotlin/classes");
File aar = new File(getModule().getRootFile(), "/build/bin/aar");
List<File> inputFolders = new ArrayList<>();
inputFolders.add(javaClasses);
inputFolders.add(kotlinClasses);
assembleAar(inputFolders, aar);
}
private void assembleAar(List<File> inputFolders, File aar)
throws IOException, CompilationFailedException {
if (!aar.exists()) {
if (!aar.mkdirs()) {
throw new IOException("Failed to create resource aar directory");
}
}
AssembleJar assembleJar = new AssembleJar(false);
assembleJar.setOutputFile(new File(aar.getAbsolutePath(), "classes.jar"));
assembleJar.setJarOptions(new JarOptionsImpl(new Attributes()));
assembleJar.createJarArchive(inputFolders);
File library = new File(getModule().getRootFile(), "/build/outputs/aar/");
if (!library.exists()) {
if (!library.mkdirs()) {
throw new IOException("Failed to create resource libs directory");
}
}
File manifest = new File(getModule().getRootFile(), "/src/main/AndroidManifest.xml");
if (manifest.exists()) {
copyResources(manifest, aar.getAbsolutePath());
}
File res = new File(getModule().getRootFile(), "/src/main/res");
if (res.exists()) {
copyResources(res, aar.getAbsolutePath());
}
File assets = new File(getModule().getRootFile(), "/src/main/assets");
File jniLibs = new File(getModule().getRootFile(), "/src/main/jniLibs");
if (assets.exists()) {
copyResources(assets, aar.getAbsolutePath());
}
if (jniLibs.exists()) {
copyResources(jniLibs, aar.getAbsolutePath());
File jni = new File(aar.getAbsolutePath(), "jniLibs");
jni.renameTo(new File(aar.getAbsolutePath(), "jni"));
}
zipFolder(
Paths.get(aar.getAbsolutePath()),
Paths.get(library.getAbsolutePath(), getModule().getRootFile().getName() + ".aar"));
if (aar.exists()) {
FileUtils.deleteDirectory(aar);
}
}
private void zipFolder(final Path sourceFolderPath, Path zipPath) throws IOException {
final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath.toFile()));
Files.walkFileTree(
sourceFolderPath,
new SimpleFileVisitor<Path>() {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString()));
Files.copy(file, zos);
zos.closeEntry();
return FileVisitResult.CONTINUE;
}
});
zos.close();
}
private void copyResources(File file, String path) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
copyResources(child, path + "/" + file.getName());
}
}
} else {
File directory = new File(path);
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Failed to create directory " + directory);
}
FileUtils.copyFileToDirectory(file, directory);
}
}
}
| 4,668 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
SignTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/apk/SignTask.java | package com.tyron.builder.compiler.apk;
import android.util.Log;
import com.android.apksig.ApkSigner;
import com.android.apksig.SignUtils;
import com.android.apksig.apk.ApkFormatException;
import com.google.common.collect.ImmutableList;
import com.tyron.builder.BuildModule;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.common.util.Decompress;
import java.io.File;
import java.io.IOException;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
public class SignTask extends Task<AndroidModule> {
private File mInputApk;
private File mOutputApk;
private BuildType mBuildType;
private File testKey;
private File testCert;
private String mStoreFile;
private String mKeyAlias;
private String mStorePassword;
private String mKeyPassword;
private HashMap<String, String> signingConfigs;
private ApkSigner.SignerConfig signerConfig;
private KeyStore mKeyStore;
public SignTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return "validateSigningConfig";
}
@Override
public void prepare(BuildType type) throws IOException {
mBuildType = type;
if (type == BuildType.AAB) {
mInputApk = new File(getModule().getBuildDirectory(), "bin/app-module-aligned.aab");
mOutputApk = new File(getModule().getBuildDirectory(), "bin/app-module-signed.aab");
if (!mInputApk.exists()) {
mInputApk = new File(getModule().getBuildDirectory(), "bin/app-module.aab");
}
if (!mInputApk.exists()) {
throw new IOException("Unable to find built aab file.");
}
} else {
mInputApk = new File(getModule().getBuildDirectory(), "bin/aligned.apk");
mOutputApk = new File(getModule().getBuildDirectory(), "bin/signed.apk");
if (!mInputApk.exists()) {
mInputApk = new File(getModule().getBuildDirectory(), "bin/generated.apk");
}
if (!mInputApk.exists()) {
throw new IOException("Unable to find generated apk file.");
}
}
signingConfigs = new HashMap<>();
Log.d(getName().toString(), "Signing APK.");
}
@Override
public void run() throws IOException, CompilationFailedException {
signingConfigs.putAll(getModule().getSigningConfigs());
if (signingConfigs == null || signingConfigs.isEmpty()) {
try {
File[] files = getModule().getRootFile().listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
if (file.getName().endsWith(".pk8")) {
testKey = file;
}
if (file.getName().endsWith(".pem")) {
testCert = file;
}
}
}
if (testKey != null && testCert != null) {
if (!testKey.exists()) {
throw new IOException(
"Unable to get custom pk8 key file in "
+ getModule().getRootFile().getAbsolutePath());
}
if (!testCert.exists()) {
throw new IOException(
"Unable to get custom pem certificate file "
+ getModule().getRootFile().getAbsolutePath());
}
getLogger().debug("> Task :" + getModule().getRootFile().getName() + ":" + "sign");
signerConfig =
SignUtils.getSignerConfig(testKey.getAbsolutePath(), testCert.getAbsolutePath());
} else {
testKey = new File(getTestKeyFile());
if (!testKey.exists()) {
throw new IOException("Unable to get test key file.");
}
testCert = new File(getTestCertFile());
if (!testCert.exists()) {
throw new IOException("Unable to get test certificate file.");
}
getLogger().debug("> Task :" + getModule().getRootFile().getName() + ":" + "sign");
signerConfig =
SignUtils.getSignerConfig(testKey.getAbsolutePath(), testCert.getAbsolutePath());
}
}
} catch (Exception e) {
throw new CompilationFailedException(e);
}
} else {
try {
for (Map.Entry<String, String> entry : signingConfigs.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key.equals("storeFile")) {
if (value == null || value.equals("") || value.isEmpty()) {
throw new CompilationFailedException("Unable to get storeFile.");
}
mStoreFile = value;
} else if (key.equals("keyAlias")) {
if (value == null || value.equals("") || value.isEmpty()) {
throw new CompilationFailedException("Unable to get keyAlias.");
}
mKeyAlias = value;
} else if (key.equals("storePassword")) {
if (value == null || value.equals("") || value.isEmpty()) {
throw new CompilationFailedException("Unable to get storePassword.");
}
mStorePassword = value;
} else if (key.equals("keyPassword")) {
if (value == null || value.equals("") || value.isEmpty()) {
throw new CompilationFailedException("Unable to get keyPassword.");
}
mKeyPassword = value;
}
}
File jks = new File(getModule().getRootFile(), mStoreFile);
if (!jks.exists()) {
throw new CompilationFailedException(
"Unable to get store file "
+ getModule().getRootFile().getAbsolutePath()
+ "/"
+ mStoreFile);
}
getLogger().debug("> Task :" + getModule().getRootFile().getName() + ":" + "sign");
mKeyStore = SignUtils.getKeyStore(jks, mStorePassword);
signerConfig = SignUtils.getSignerConfig(mKeyStore, mKeyAlias, mKeyPassword);
} catch (Exception e) {
throw new CompilationFailedException(e);
}
}
try {
ApkSigner apkSigner =
new ApkSigner.Builder(ImmutableList.of(signerConfig))
.setInputApk(mInputApk)
.setOutputApk(mOutputApk)
.setMinSdkVersion(getModule().getMinSdk())
.build();
apkSigner.sign();
} catch (ApkFormatException e) {
throw new CompilationFailedException(e.toString());
} catch (Exception e) {
throw new CompilationFailedException(e);
}
FileUtils.forceDelete(mInputApk);
}
private String getTestKeyFile() {
File check = new File(BuildModule.getContext().getFilesDir() + "/temp/testkey.pk8");
if (check.exists()) {
return check.getAbsolutePath();
}
Decompress.unzipFromAssets(
BuildModule.getContext(), "testkey.pk8.zip", check.getParentFile().getAbsolutePath());
return check.getAbsolutePath();
}
private String getTestCertFile() {
File check = new File(BuildModule.getContext().getFilesDir() + "/temp/testkey.x509.pem");
if (check.exists()) {
return check.getAbsolutePath();
}
Decompress.unzipFromAssets(
BuildModule.getContext(), "testkey.x509.pem.zip", check.getParentFile().getAbsolutePath());
return check.getAbsolutePath();
}
}
| 7,573 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ZipAlignTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/apk/ZipAlignTask.java | package com.tyron.builder.compiler.apk;
import android.content.Context;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.model.DiagnosticWrapper;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.common.ApplicationProvider;
import com.tyron.common.util.BinaryExecutor;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.tools.Diagnostic;
public class ZipAlignTask extends Task<AndroidModule> {
private static final String TAG = "zipAlign";
private File mApkFile;
private File mOutputApk;
private BuildType mBuildType;
public ZipAlignTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
mBuildType = type;
if (type == BuildType.AAB) {
mApkFile = new File(getModule().getBuildDirectory(), "bin/app-module.aab");
mOutputApk = new File(getModule().getBuildDirectory(), "bin/app-module-aligned.aab");
if (!mApkFile.exists()) {
throw new IOException("Unable to find built aab file in projects build path");
}
} else {
mApkFile = new File(getModule().getBuildDirectory(), "bin/generated.apk");
mOutputApk = new File(getModule().getBuildDirectory(), "bin/aligned.apk");
if (!mApkFile.exists()) {
throw new IOException("Unable to find generated apk file in projects build path");
}
}
}
@Override
public void run() throws IOException, CompilationFailedException {
File binary = getZipAlignBinary();
List<String> args = new ArrayList<>();
args.add(binary.getAbsolutePath());
args.add("-f");
args.add("4");
args.add(mApkFile.getAbsolutePath());
args.add(mOutputApk.getAbsolutePath());
BinaryExecutor executor = new BinaryExecutor();
executor.setCommands(args);
List<DiagnosticWrapper> wrappers = new ArrayList<>();
String logs = executor.execute();
if (!logs.isEmpty()) {
String[] lines = logs.split("\n");
if (lines.length == 0) {
lines = new String[] {logs};
}
for (String line : lines) {
Diagnostic.Kind kind = getKind(line);
if (line.contains(":")) {
line = line.substring(line.indexOf(':'));
}
DiagnosticWrapper wrapper = new DiagnosticWrapper();
wrapper.setLineNumber(-1);
wrapper.setColumnNumber(-1);
wrapper.setStartPosition(-1);
wrapper.setEndPosition(-1);
wrapper.setKind(kind);
wrapper.setMessage(line);
wrappers.add(wrapper);
}
}
boolean hasErrors = wrappers.stream().anyMatch(it -> it.getKind() == Diagnostic.Kind.ERROR);
if (hasErrors) {
throw new CompilationFailedException("Check logs for more details.");
}
}
private Diagnostic.Kind getKind(String string) {
String trimmed = string.trim();
if (trimmed.startsWith("WARNING")) {
return Diagnostic.Kind.WARNING;
} else if (trimmed.startsWith("ERROR")) {
return Diagnostic.Kind.ERROR;
} else {
return Diagnostic.Kind.NOTE;
}
}
private File getZipAlignBinary() throws IOException {
Context context = ApplicationProvider.getApplicationContext();
String path = context.getApplicationInfo().nativeLibraryDir + "/libzipalign.so";
File file = new File(path);
if (!file.exists()) {
throw new IOException("ZipAlign binary not found.");
}
return file;
}
}
| 3,757 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
PackageTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/apk/PackageTask.java | package com.tyron.builder.compiler.apk;
import android.net.Uri;
import android.util.Log;
import com.android.sdklib.build.ApkBuilder;
import com.android.sdklib.build.ApkCreationException;
import com.android.sdklib.build.DuplicateFileException;
import com.android.sdklib.build.SealedApkException;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PackageTask extends Task<AndroidModule> {
/** List of extra dex files not including the main dex file */
private final List<File> mDexFiles = new ArrayList<>();
/** List of each jar files of libraries */
private final List<File> mLibraries = new ArrayList<>();
private final List<File> mNativeLibraries = new ArrayList<>();
/** Main dex file */
private File mDexFile;
/** The generated.apk.res file */
private File mGeneratedRes;
/** The output apk file */
private File mApk;
private BuildType mBuildType;
public PackageTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return "package";
}
@Override
public void prepare(BuildType type) throws IOException {
mBuildType = type;
File mBinDir = new File(getModule().getBuildDirectory(), "bin");
mApk = new File(mBinDir, "generated.apk");
mDexFile = new File(mBinDir, "classes.dex");
mGeneratedRes = new File(mBinDir, "generated.apk.res");
if (!mGeneratedRes.exists()) {
mGeneratedRes.createNewFile();
}
File[] binFiles = mBinDir.listFiles();
if (binFiles != null) {
for (File child : binFiles) {
if (!child.isFile()) {
continue;
}
if (!child.getName().equals("classes.dex") && child.getName().endsWith(".dex")) {
mDexFiles.add(child);
}
}
}
mLibraries.addAll(getModule().getLibraries());
mNativeLibraries.addAll(getModule().getNativeLibraries());
Log.d(getName().toString(), "Packaging APK.");
}
@Override
public void run() throws IOException, CompilationFailedException {
int dexCount = 1;
try {
ApkBuilder builder =
new ApkBuilder(
mApk.getAbsolutePath(),
mGeneratedRes.getAbsolutePath(),
mDexFile.getAbsolutePath(),
null,
null);
for (File extraDex : mDexFiles) {
dexCount++;
builder.addFile(extraDex, Uri.parse(extraDex.getAbsolutePath()).getLastPathSegment());
}
for (File library : mLibraries) {
builder.addResourcesFromJar(library);
File parent = library.getParentFile();
if (parent != null) {
File jniFolder = new File(parent, "jni");
if (jniFolder.exists() && jniFolder.isDirectory()) {
builder.addNativeLibraries(jniFolder);
}
}
}
for (File library : mNativeLibraries) {
File parent = library.getParentFile();
if (parent != null) {
File jniFolder = new File(parent, "jni");
if (jniFolder.exists() && jniFolder.isDirectory()) {
builder.addNativeLibraries(jniFolder);
}
}
}
if (getModule().getNativeLibrariesDirectory().exists()) {
builder.addNativeLibraries(getModule().getNativeLibrariesDirectory());
}
if (mBuildType == BuildType.DEBUG) {
builder.setDebugMode(true);
// For debug mode, dex files are not merged to save up compile time
for (File it : getModule().getLibraries()) {
File parent = it.getParentFile();
if (parent != null) {
File[] dexFiles = parent.listFiles(c -> c.getName().endsWith(".dex"));
if (dexFiles != null) {
for (File dexFile : dexFiles) {
dexCount++;
builder.addFile(dexFile, "classes" + dexCount + ".dex");
}
}
}
}
}
File resourcesDir = getModule().getResourcesDir();
if (resourcesDir.exists()) {
builder.addSourceFolder(resourcesDir);
}
List<String> excludes = getModule().getExcludes();
if (excludes != null && !excludes.isEmpty()) {
for (String exclude : excludes) {
// builder.addNoCompressPattern(exclude);
}
}
builder.sealApk();
} catch (ApkCreationException | SealedApkException e) {
throw new CompilationFailedException(e);
} catch (DuplicateFileException e) {
String message = "Duplicate files from two libraries detected. \n";
message += "File1: " + e.getFile1() + " \n";
message += "File2: " + e.getFile2() + " \n";
message += "Archive path: " + e.getArchivePath();
throw new CompilationFailedException(message);
}
}
}
| 5,084 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ExtractApksTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/aab/ExtractApksTask.java | package com.tyron.builder.compiler.aab;
import android.util.Log;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.BundleTool;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ExtractApksTask extends Task<AndroidModule> {
public ExtractApksTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
private static final String TAG = "extractApks";
@Override
public String getName() {
return TAG;
}
private File mBinDir;
private File mOutputApk;
private File mOutputApks;
@Override
public void prepare(BuildType type) throws IOException {
mBinDir = new File(getModule().getBuildDirectory(), "/bin");
mOutputApk = new File(mBinDir.getAbsolutePath() + "/app-module-signed.aab");
if (!mOutputApk.exists()) {
throw new IOException("Unable to find signed aab file.");
}
mOutputApks = new File(mBinDir.getAbsolutePath() + "/app.apks");
}
public void run() throws IOException, CompilationFailedException {
try {
buildApks();
extractApks();
} catch (IOException e) {
throw new CompilationFailedException(e);
}
}
private void extractApks() throws IOException {
Log.d(TAG, "Extracting Apks");
String Apks = mBinDir.getAbsolutePath() + "/app.apks";
String dApks = mBinDir.getAbsolutePath() + "";
uApks(Apks, dApks);
}
private static void uApks(String Apks, String dApks) throws IOException {
File dir = new File(dApks);
// create output directory if it doesn't exist
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Failed to create directory: " + dir);
}
try (FileInputStream fis = new FileInputStream(Apks)) {
byte[] buffer = new byte[1024];
try (ZipInputStream zis = new ZipInputStream(fis)) {
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(dApks + File.separator + fileName);
// create directories for sub directories in zip
File parent = newFile.getParentFile();
if (parent != null) {
if (!parent.exists() && !parent.mkdirs()) {
throw new IOException("Failed to create directories: " + parent);
}
}
try (FileOutputStream fos = new FileOutputStream(newFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
ze = zis.getNextEntry();
}
}
}
}
private void buildApks() throws CompilationFailedException {
Log.d(TAG, "Building Apks");
BundleTool signer = new BundleTool(mOutputApk.getAbsolutePath(), mOutputApks.getAbsolutePath());
try {
signer.apk();
} catch (Exception e) {
throw new CompilationFailedException(e);
}
}
}
| 3,280 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AabTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/aab/AabTask.java | package com.tyron.builder.compiler.aab;
import static com.android.sdklib.build.ApkBuilder.checkFileForPackaging;
import static com.android.sdklib.build.ApkBuilder.checkFolderForPackaging;
import android.util.Log;
import com.android.sdklib.build.DuplicateFileException;
import com.android.sdklib.internal.build.SignedJarBuilder;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.BundleTool;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.compiler.manifest.SdkConstants;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.common.util.BinaryExecutor;
import com.tyron.common.util.Decompress;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import org.apache.commons.io.FileUtils;
public class AabTask extends Task<AndroidModule> {
public AabTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
private static final String TAG = "bundleRelease";
private File mBinDir;
private File base;
private File manifest;
private final JavaAndNativeResourceFilter mFilter = new JavaAndNativeResourceFilter();
private final HashMap<String, File> mAddedFiles = new HashMap<>();
@Override
public String getName() {
return TAG;
}
private File mInputApk;
private File mOutputApk;
private File mOutputApks;
@Override
public void prepare(BuildType type) throws IOException {
mBinDir = new File(getModule().getBuildDirectory(), "/bin");
base = new File(mBinDir.getAbsolutePath(), "/base");
if (!base.exists() && !base.mkdirs()) {
throw new IOException("Failed to create resource output directory");
}
manifest = new File(mBinDir.getAbsolutePath(), "/base/manifest");
if (!manifest.exists() && !manifest.mkdirs()) {
throw new IOException("Failed to create resource output directory");
}
File dex = new File(mBinDir.getAbsolutePath(), "/base/dex");
if (!dex.exists() && !dex.mkdirs()) {
throw new IOException("Failed to create resource output directory");
}
mInputApk = new File(mBinDir.getAbsolutePath() + "/app-module.zip");
mOutputApk = new File(mBinDir.getAbsolutePath() + "/app-module.aab");
mOutputApks = new File(mBinDir.getAbsolutePath() + "/app.apks");
mAddedFiles.clear();
}
public void run() throws IOException, CompilationFailedException {
try {
unZip();
copyResources();
copyManifest();
copyJni();
copyDexFiles();
baseZip();
copyLibraries();
aab();
} catch (SignedJarBuilder.IZipEntryFilter.ZipAbortException e) {
String message = e.getMessage();
if (e instanceof DuplicateFileException) {
DuplicateFileException duplicateFileException = (DuplicateFileException) e;
message +=
"\n"
+ "file 1: "
+ duplicateFileException.getFile1()
+ "\n"
+ "file 2: "
+ duplicateFileException.getFile2()
+ "\n"
+ "path: "
+ duplicateFileException.getArchivePath();
}
throw new CompilationFailedException(message);
}
}
@Override
protected void clean() {
try {
FileUtils.deleteDirectory(base);
} catch (IOException ignore) {
}
}
private void aab() throws CompilationFailedException {
Log.d(TAG, "Generating AAB.");
boolean uncompressed = false;
BundleTool signer = new BundleTool(mInputApk.getAbsolutePath(), mOutputApk.getAbsolutePath());
try {
if (getModule().getUseLegacyPackaging()) {
uncompressed = true;
signer.aab(uncompressed);
} else {
uncompressed = false;
signer.aab(uncompressed);
}
} catch (Exception e) {
throw new CompilationFailedException(e);
}
}
private void baseZip() throws IOException {
Log.d(TAG, "Creating Module Archive");
String folderToZip = base.getAbsolutePath();
String zipName = mBinDir.getAbsolutePath() + "/app-module.zip";
zipFolder(Paths.get(folderToZip), Paths.get(zipName));
}
// Uses java.util.zip to create zip file
private void zipFolder(final Path sourceFolderPath, Path zipPath) throws IOException {
final ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath.toFile()));
Files.walkFileTree(
sourceFolderPath,
new SimpleFileVisitor<Path>() {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
zos.putNextEntry(new ZipEntry(sourceFolderPath.relativize(file).toString()));
Files.copy(file, zos);
zos.closeEntry();
return FileVisitResult.CONTINUE;
}
});
zos.close();
}
private void copyManifest() throws CompilationFailedException {
Log.d(TAG, "Copying Manifest.");
List<String> args = new ArrayList<>();
args.add("mv");
args.add(base.getAbsolutePath() + "/AndroidManifest.xml");
args.add(manifest.getAbsolutePath() + "");
BinaryExecutor executor = new BinaryExecutor();
executor.setCommands(args);
if (!executor.execute().isEmpty()) {
throw new CompilationFailedException(executor.getLog());
}
}
private void copyDexFiles() throws IOException {
File[] dexFiles = mBinDir.listFiles(c -> c.isFile() && c.getName().endsWith(".dex"));
File dexOutput = new File(mBinDir, "base/dex");
if (dexFiles != null) {
for (File dexFile : dexFiles) {
FileUtils.copyFileToDirectory(dexFile, dexOutput);
}
}
}
private void copyJni() throws IOException {
Log.d(TAG, "Coping JniLibs.");
String fromDirectory = getModule().getNativeLibrariesDirectory().getAbsolutePath();
String toToDirectory = base.getAbsolutePath() + "/lib";
copyDirectoryFileVisitor(fromDirectory, toToDirectory);
List<File> libraries = getModule().getLibraries();
for (File library : libraries) {
File parent = library.getParentFile();
if (parent == null) {
continue;
}
File jniDir = new File(parent, "jni");
if (jniDir.exists()) {
fromDirectory = jniDir.getAbsolutePath();
copyDirectoryFileVisitor(fromDirectory, toToDirectory);
}
}
}
private void copyResources()
throws IOException, SignedJarBuilder.IZipEntryFilter.ZipAbortException {
File resourcesDir = getModule().getResourcesDir();
File[] files = resourcesDir.listFiles();
if (files != null) {
for (File file : files) {
copyResources(file, "root");
}
}
}
private void copyResources(File file, String path) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
copyResources(child, path + "/" + file.getName());
}
}
} else {
File directory = new File(base, path);
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Failed to create directory " + directory);
}
FileUtils.copyFileToDirectory(file, directory);
}
}
private void copyLibraries()
throws IOException, SignedJarBuilder.IZipEntryFilter.ZipAbortException {
List<File> libraryJars = getModule().getLibraries();
File originalFile = new File(mBinDir, "app-module.zip");
try (ZipFile zipFile = new ZipFile(originalFile)) {
for (File libraryJar : libraryJars) {
if (!libraryJar.exists()) {
continue;
}
mFilter.reset(libraryJar);
try (JarFile jarFile = new JarFile(libraryJar)) {
Enumeration<JarEntry> entries = jarFile.entries();
jar:
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String name = "root/" + jarEntry.getName();
String[] names = name.split("/");
if (names.length == 0) {
continue;
}
for (String s : names) {
boolean checkFolder = checkFolderForPackaging(s);
if (!checkFolder) {
continue jar;
}
}
if (jarEntry.isDirectory() || jarEntry.getName().startsWith("META-INF")) {
continue;
}
boolean b = mFilter.checkEntry(name);
if (!b) {
continue;
}
InputStream inputStream = jarFile.getInputStream(jarEntry);
ZipParameters zipParameters = new ZipParameters();
zipParameters.setFileNameInZip(name);
zipParameters.setCompressionLevel(CompressionLevel.FASTEST);
zipFile.addStream(inputStream, zipParameters);
}
} catch (ZipException e) {
e.printStackTrace();
}
}
}
}
public static void copyDirectoryFileVisitor(String source, String target) throws IOException {
TreeCopyFileVisitor fileVisitor = new TreeCopyFileVisitor(source, target);
Files.walkFileTree(Paths.get(source), fileVisitor);
}
private void unZip() {
Log.d(TAG, "Unzipping proto format.");
String zipFilePath = mBinDir.getAbsolutePath() + "/proto-format.zip";
String destDir = base.getAbsolutePath() + "";
Decompress.unzip(zipFilePath, destDir);
}
/**
* Custom {@link SignedJarBuilder.IZipEntryFilter} to filter out everything that is not a standard
* java resources, and also record whether the zip file contains native libraries.
*
* <p>Used in {@link SignedJarBuilder#writeZip(java.io.InputStream,
* SignedJarBuilder.IZipEntryFilter)} when we only want the java resources from external jars.
*/
private final class JavaAndNativeResourceFilter implements SignedJarBuilder.IZipEntryFilter {
private final List<String> mNativeLibs = new ArrayList<String>();
private boolean mNativeLibsConflict = false;
private File mInputFile;
@Override
public boolean checkEntry(String archivePath) throws ZipAbortException {
// split the path into segments.
String[] segments = archivePath.split("/");
// empty path? skip to next entry.
if (segments.length == 0) {
return false;
}
// Check each folders to make sure they should be included.
// Folders like CVS, .svn, etc.. should already have been excluded from the
// jar file, but we need to exclude some other folder (like /META-INF) so
// we check anyway.
for (int i = 0; i < segments.length - 1; i++) {
if (!checkFolderForPackaging(segments[i])) {
return false;
}
}
// get the file name from the path
String fileName = segments[segments.length - 1];
boolean check = checkFileForPackaging(fileName);
// only do additional checks if the file passes the default checks.
if (check) {
File duplicate = checkFileForDuplicate(archivePath);
if (duplicate != null) {
throw new DuplicateFileException(archivePath, duplicate, mInputFile);
} else {
mAddedFiles.put(archivePath, mInputFile);
}
if (archivePath.endsWith(".so") || archivePath.endsWith(".bc")) {
mNativeLibs.add(archivePath);
// only .so located in lib/ will interfere with the installation
if (archivePath.startsWith(SdkConstants.FD_APK_NATIVE_LIBS + "/")) {
mNativeLibsConflict = true;
}
} else if (archivePath.endsWith(".jnilib")) {
mNativeLibs.add(archivePath);
}
}
return check;
}
List<String> getNativeLibs() {
return mNativeLibs;
}
boolean getNativeLibsConflict() {
return mNativeLibsConflict;
}
void reset(File inputFile) {
mInputFile = inputFile;
mNativeLibs.clear();
mNativeLibsConflict = false;
}
}
private File checkFileForDuplicate(String archivePath) {
return mAddedFiles.get(archivePath);
}
}
| 12,819 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
TreeCopyFileVisitor.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/aab/TreeCopyFileVisitor.java | package com.tyron.builder.compiler.aab;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
public class TreeCopyFileVisitor extends SimpleFileVisitor<Path> {
private final Path source;
private final Path target;
public TreeCopyFileVisitor(String source, String target) {
this.source = Paths.get(source);
this.target = Paths.get(target);
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Path resolve = target.resolve(source.relativize(dir));
if (Files.notExists(resolve)) {
Files.createDirectories(resolve);
System.out.println("Create directories : " + resolve);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path resolve = target.resolve(source.relativize(file));
Files.copy(file, resolve);
System.out.printf("Copy File from \t'%s' to \t'%s'%n", file, resolve);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.format("Unable to copy: %s: %s%n", file, exc);
return FileVisitResult.CONTINUE;
}
}
| 1,275 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
InjectLoggerTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/log/InjectLoggerTask.java | package com.tyron.builder.compiler.log;
import android.util.Log;
import android.util.Pair;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.common.util.StringSearch;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.openjdk.javax.xml.parsers.DocumentBuilder;
import org.openjdk.javax.xml.parsers.DocumentBuilderFactory;
import org.openjdk.javax.xml.parsers.ParserConfigurationException;
import org.openjdk.javax.xml.transform.Transformer;
import org.openjdk.javax.xml.transform.TransformerException;
import org.openjdk.javax.xml.transform.TransformerFactory;
import org.openjdk.javax.xml.transform.dom.DOMSource;
import org.openjdk.javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class InjectLoggerTask extends Task<AndroidModule> {
private static final String TAG = "injectLogger";
private static final String APPLICATION_CLASS =
"\nimport android.app.Application;\n"
+ "public class LoggerApplication extends Application {\n"
+ " public void onCreate() {\n"
+ " super.onCreate();\n"
+ " }\n"
+ "}";
private static final String LOGGER_CLASS =
"import android.content.Context;\n"
+ "import android.content.Intent;\n"
+ "\n"
+ "import java.io.BufferedReader;\n"
+ "import java.io.IOException;\n"
+ "import java.io.InputStreamReader;\n"
+ "import java.util.concurrent.Executors;\n"
+ "import java.util.regex.Matcher;\n"
+ "import java.util.regex.Pattern;\n"
+ "\n"
+ "public class Logger {\n"
+ "\n"
+ " private static final String DEBUG = \"DEBUG\";\n"
+ " private static final String WARNING = \"WARNING\";\n"
+ " private static final String ERROR = \"ERROR\";\n"
+ " private static final String INFO = \"INFO\";\n"
+ " private static final Pattern TYPE_PATTERN = Pattern.compile(\"^(.*\\\\d) ([ADEIW]) (.*): (.*)\");\n"
+ "\n"
+ " private static volatile boolean mInitialized;\n"
+ " private static Context mContext;\n"
+ "\n"
+ " public static void initialize(Context context) {\n"
+ " if (mInitialized) {\n"
+ " return;\n"
+ " }\n"
+ " mInitialized = true;\n"
+ " mContext = context.getApplicationContext();\n"
+ "\n"
+ " start();\n"
+ " }\n"
+ "\n"
+ " private static void start() {\n"
+ " Executors.newSingleThreadExecutor().execute(() -> {\n"
+ " try {\n"
+ " clear();\n"
+ " Process process = Runtime.getRuntime()\n"
+ " .exec(\"logcat\");\n"
+ " BufferedReader reader = new BufferedReader(new InputStreamReader(\n"
+ " process.getInputStream()));\n"
+ " String line = null;\n"
+ " while ((line = reader.readLine()) != null) {\n"
+ " Matcher matcher = TYPE_PATTERN.matcher(line);\n"
+ " if (matcher.matches()) {\n"
+ " String type = matcher.group(2);\n"
+ " if (type != null) {\n"
+ " switch (type) {\n"
+ " case \"D\": debug(line); break;\n"
+ " case \"E\": error(line); break;\n"
+ " case \"W\": warning(line); break;\n"
+ " case \"I\": info(line); break;\n"
+ " }\n"
+ " } else {\n"
+ " debug(line);\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " } catch (IOException e) {\n"
+ " error(String.format(\"IOException occurred on Logger: \", e.getMessage()));\n"
+ " }\n"
+ " });\n"
+ " }\n"
+ "\n"
+ " private static void clear() throws IOException {\n"
+ " Runtime.getRuntime().exec(\"logcat -c\");\n"
+ " }\n"
+ "\n"
+ " private static void debug(String message) {\n"
+ " broadcast(DEBUG, message);\n"
+ " }\n"
+ "\n"
+ " private static void warning(String message) {\n"
+ " broadcast(WARNING, message);\n"
+ " }\n"
+ "\n"
+ " private static void error(String message) {\n"
+ " broadcast(ERROR, message);\n"
+ " }\n"
+ "\n"
+ " private static void info(String message) {\n"
+ " broadcast(INFO, message);\n"
+ " }\n"
+ "\n"
+ " private static void broadcast(String type, String message) {\n"
+ " StringBuilder intentAction = new StringBuilder();\n"
+ " intentAction.append(mContext.getPackageName()).append(\".LOG\");\n"
+ " Intent intent = new Intent(intentAction.toString());\n"
+ " intent.putExtra(\"type\", type);\n"
+ " intent.putExtra(\"message\", message);\n"
+ " mContext.sendBroadcast(intent);\n"
+ " }\n"
+ "}\n";
private File mLoggerFile;
private File mApplicationFile;
private String mOriginalApplication;
public InjectLoggerTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
getModule().getJavaFiles();
getModule().getKotlinFiles();
}
@Override
public void run() throws IOException, CompilationFailedException {
try {
addLoggerClass();
boolean isNewApplicationClass = true;
String applicationClass = getApplicationClass();
if (applicationClass == null) {
applicationClass = getApplicationId() + ".LoggerApplication";
createApplicationClass(applicationClass);
} else {
isNewApplicationClass = false;
}
mApplicationFile = getModule().getJavaFile(applicationClass);
if (mApplicationFile == null) {
mApplicationFile = getModule().getKotlinFile(applicationClass);
}
if (mApplicationFile == null) {
String message =
""
+ "Unable to find the application class defined in manifest.\n"
+ "fully qualified name: "
+ applicationClass
+ '\n'
+ "This build will not have logger injected.";
getLogger().warning(message);
return;
}
if (!isNewApplicationClass) {
mOriginalApplication =
FileUtils.readFileToString(mApplicationFile, Charset.defaultCharset());
}
injectLogger(mApplicationFile);
Log.d(TAG, "application class: " + applicationClass);
} catch (RuntimeException
| XmlPullParserException
| ParserConfigurationException
| SAXException
| TransformerException e) {
throw new CompilationFailedException(Log.getStackTraceString(e));
}
}
@Override
protected void clean() {
if (mApplicationFile != null) {
if (mOriginalApplication != null) {
try {
FileUtils.writeStringToFile(
mApplicationFile, mOriginalApplication, Charset.defaultCharset());
} catch (IOException ignore) {
}
} else {
try {
getModule().removeJavaFile(StringSearch.packageName(mApplicationFile));
FileUtils.delete(mApplicationFile);
} catch (IOException e) {
Log.e(TAG, "Failed to delete application class: " + e.getMessage());
}
}
}
if (mLoggerFile != null) {
try {
getModule().removeJavaFile(StringSearch.packageName(mLoggerFile));
FileUtils.delete(mLoggerFile);
} catch (IOException e) {
Log.e(TAG, "Failed to delete logger class: " + e.getMessage());
}
}
}
private String getApplicationClass()
throws XmlPullParserException,
IOException,
ParserConfigurationException,
SAXException,
TransformerException {
File manifest =
new File(
getModule().getBuildDirectory().getAbsolutePath().replaceAll("%20", " "),
"bin/AndroidManifest.xml");
XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(new FileInputStream(manifest), null);
final int depth = parser.getDepth();
int type;
while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
&& type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
if (parser.getName().equals("application")) {
List<Pair<String, String>> attributes = new ArrayList<>();
for (int i = 0; i < parser.getAttributeCount(); i++) {
attributes.add(Pair.create(parser.getAttributeName(i), parser.getAttributeValue(i)));
}
for (Pair<String, String> pair : attributes) {
if (pair.first.equals("android:name")) {
String name = pair.second;
if (name.startsWith(".")) {
return getApplicationId() + name;
} else {
return name;
}
}
}
}
}
return null;
}
private void createApplicationClass(String name)
throws IOException, ParserConfigurationException, TransformerException, SAXException {
Log.d(TAG, "Creating application class " + name);
File manifest =
new File(
getModule().getBuildDirectory().getAbsolutePath().replaceAll("%20", " "),
"bin/AndroidManifest.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
Document document = documentBuilder.parse(manifest);
Element app = (Element) document.getElementsByTagName("application").item(0);
app.setAttribute("android:name", name);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
transformer.transform(source, new StreamResult(manifest.getAbsolutePath()));
File directory = getModule().getJavaDirectory();
File output = new File(directory, name.replace('.', '/') + ".java");
if (!output.exists() && !output.createNewFile()) {
throw new IOException("Unable to create LoggerApplication");
}
String classString = "package " + getApplicationId() + ";\n" + APPLICATION_CLASS;
FileUtils.writeStringToFile(output, classString, Charset.defaultCharset());
getModule().addJavaFile(output);
}
private void injectLogger(File applicationClass) throws IOException, CompilationFailedException {
String applicationContents =
FileUtils.readFileToString(applicationClass, Charset.defaultCharset());
if (applicationContents.contains("Logger.initialize(this);")) {
Log.d(TAG, "Application class already initializes Logger");
return;
}
String onCreateString = "super.onCreate()";
int index = applicationContents.indexOf(onCreateString);
if (index == -1) {
throw new CompilationFailedException("No super method for Application.onCreate() found");
}
String before = applicationContents.substring(0, index + onCreateString.length() + 1);
String after = applicationContents.substring(index + onCreateString.length());
String injected = before + "\n" + "Logger.initialize(this);\n" + after;
FileUtils.writeStringToFile(applicationClass, injected, Charset.defaultCharset());
}
private void addLoggerClass() throws IOException {
Log.d(TAG, "Creating Logger.java");
File packageDir =
new File(getModule().getJavaDirectory(), getApplicationId().replace('.', '/'));
File loggerClass = new File(packageDir, "/Logger.java");
if (packageDir.exists()) {
} else {
packageDir.mkdirs();
}
if (!loggerClass.exists() && !loggerClass.createNewFile()) {
throw new IOException("Unable to create Logger.java");
}
String loggerString = "package " + getApplicationId() + ";\n" + LOGGER_CLASS;
FileUtils.writeStringToFile(loggerClass, loggerString, Charset.defaultCharset());
mLoggerFile = loggerClass;
getModule().addJavaFile(loggerClass);
}
private String getApplicationId() throws IOException {
String packageName = getModule().getNameSpace();
String content = parseString(getModule().getGradleFile());
if (content != null) {
if (content.contains("namespace") && !content.contains("applicationId")) {
throw new IOException(
"Unable to find applicationId in "
+ getModule().getRootFile().getName()
+ "/build.gradle file");
} else if (content.contains("applicationId") && content.contains("namespace")) {
return packageName;
} else if (content.contains("applicationId") && !content.contains("namespace")) {
packageName = getModule().getApplicationId();
} else {
throw new IOException(
"Unable to find namespace or applicationId in "
+ getModule().getRootFile().getName()
+ "/build.gradle file");
}
} else {
throw new IOException(
"Unable to read " + getModule().getRootFile().getName() + "/build.gradle file");
}
return packageName;
}
private String parseString(File gradle) {
if (gradle != null && gradle.exists()) {
try {
String readString = FileUtils.readFileToString(gradle, Charset.defaultCharset());
if (readString != null && !readString.isEmpty()) {
return readString;
}
} catch (IOException e) {
// handle the exception here, if needed
}
}
return null;
}
}
| 15,091 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
GenerateFirebaseConfigTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/firebase/GenerateFirebaseConfigTask.java | package com.tyron.builder.compiler.firebase;
import android.util.Log;
import androidx.annotation.VisibleForTesting;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GenerateFirebaseConfigTask extends Task<AndroidModule> {
private static final String TAG = "generateFirebaseConfig";
private static final String VALUES = "values";
private static final String CLIENT = "client";
private static final String API_KEY = "api_key";
private static final String CLIENT_ID = "client_id";
private static final String CLIENT_INFO = "client_info";
private static final String CURRENT_KEY = "current_key";
private static final String OAUTH_CLIENT = "oauth_client";
private static final String PROJECT_INFO = "project_info";
private static final String PACKAGE_NAME = "package_name";
private static final String STORAGE_BUCKET = "storage_bucket";
private static final String FIREBASE_URL = "firebase_url";
private static final String FIREBASE_DATABASE_URL = "firebase_database_url";
private static final String ANDROID_CLIENT_INFO = "android_client_info";
private static final String MOBILESDK_SDK_APP_ID = "mobilesdk_app_id";
private static final String DEFAULT_WEB_CLIENT_ID = "default_web_client_id";
private static final String GOOGLE_SERVICES_JSON = "google-services.json";
private static final String GOOGLE_STORAGE_BUCKET = "google_storage_bucket";
private static final String GOOGLE_API_KEY = "google_api_key";
private static final String GOOGLE_APP_ID = "google_app_id";
private static final String GOOGLE_CRASH_REPORTING_API_KEY = "google_crash_reporting_api_key";
public GenerateFirebaseConfigTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
private File mConfigFile;
@Override
public void prepare(BuildType type) throws IOException {
mConfigFile = new File(getModule().getRootFile(), GOOGLE_SERVICES_JSON);
}
/**
* Processes google-services.json and outputs it to res/xml
*
* <p>According to https://firebase.google.com/docs/reference/gradle/#processing_the_json_file
*/
@Override
public void run() throws IOException, CompilationFailedException {
if (!mConfigFile.exists()) {
Log.d(TAG, "No google-services.json found.");
return;
}
String packageName = getApplicationId();
String contents = FileUtils.readFileToString(mConfigFile, Charset.defaultCharset());
try {
File xmlDirectory = new File(getModule().getAndroidResourcesDirectory(), VALUES);
if (!xmlDirectory.exists() && !xmlDirectory.mkdirs()) {
throw new IOException("Unable to create xml folder");
}
File secretsFile = new File(xmlDirectory, "secrets.xml");
if (!secretsFile.exists() && !secretsFile.createNewFile()) {
throw new IOException("Unable to create secrets.xml file");
}
if (doGenerate(contents, packageName, secretsFile)) {
return;
}
String message =
""
+ "Unable to find "
+ packageName
+ " in google-services.json. \n"
+ "Ensure that the package name defined in your firebase console "
+ "matches your app's package name.";
throw new CompilationFailedException(message);
} catch (JSONException e) {
throw new CompilationFailedException(
"Failed to parse google-services.json: " + e.getMessage());
}
}
@VisibleForTesting
public boolean doGenerate(String contents, String packageName, File secretsFile)
throws JSONException, IOException {
JSONObject jsonObject = new JSONObject(contents);
JSONObject projectInfo = jsonObject.getJSONObject(PROJECT_INFO);
JSONArray clientArray = jsonObject.getJSONArray(CLIENT);
for (int i = 0; i < clientArray.length(); i++) {
JSONObject object = clientArray.getJSONObject(i);
JSONObject clientInfo = object.getJSONObject(CLIENT_INFO);
JSONObject androidClientInfo = clientInfo.getJSONObject(ANDROID_CLIENT_INFO);
String clientPackageName = androidClientInfo.getString(PACKAGE_NAME);
if (packageName.equals(clientPackageName)) {
parseConfig(projectInfo, object, clientInfo, secretsFile);
return true;
}
}
return false;
}
private void parseConfig(
JSONObject projectInfo, JSONObject client, JSONObject clientInfo, File secretsFile)
throws JSONException, IOException {
Iterator<String> keys = projectInfo.keys();
Map<String, String> map = new HashMap<>();
keys.forEachRemaining(
s -> {
String replacedKey = replaceKey(s);
try {
map.put(replacedKey, projectInfo.getString(s));
} catch (JSONException e) {
String message =
""
+ "Failed to put value to secrets.xml.\n"
+ "Key: "
+ s
+ "\n"
+ "Error: "
+ e.getMessage();
getLogger().warning(message);
}
});
try {
String mobileSdkAppId = clientInfo.getString(MOBILESDK_SDK_APP_ID);
map.put(GOOGLE_APP_ID, mobileSdkAppId);
} catch (JSONException ignored) {
}
try {
String oathClientId = client.getJSONObject(OAUTH_CLIENT).getString(CLIENT_ID);
map.put(DEFAULT_WEB_CLIENT_ID, oathClientId);
} catch (JSONException ignore) {
}
try {
String apiKey = client.getJSONArray(API_KEY).getJSONObject(0).getString(CURRENT_KEY);
map.put(GOOGLE_API_KEY, apiKey);
map.put(GOOGLE_CRASH_REPORTING_API_KEY, apiKey);
} catch (JSONException e) {
getLogger().warning("Unable to put api keys, error: " + e.getMessage());
}
generateXML(map, secretsFile);
}
private void generateXML(Map<String, String> config, File secretsFile) throws IOException {
try (BufferedWriter writer = Files.newBufferedWriter(secretsFile.toPath())) {
writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
writer.write("<resources>\n");
writer.write("\t<integer name=\"google_play_services_version\">12451000</integer>\n");
for (Map.Entry<String, String> entry : config.entrySet()) {
writer.write("\t<string name=\"");
writer.write(entry.getKey());
writer.write("\" translatable=\"false\">");
writer.write(entry.getValue());
writer.write("</string>\n");
}
writer.write("</resources>");
}
}
private String replaceKey(String key) {
if (STORAGE_BUCKET.equals(key)) {
return GOOGLE_STORAGE_BUCKET;
}
if (FIREBASE_URL.equals(key)) {
return FIREBASE_DATABASE_URL;
}
return key;
}
private String getApplicationId() throws IOException {
String packageName = getModule().getNameSpace();
String content = parseString(getModule().getGradleFile());
if (content != null) {
if (content.contains("namespace") && !content.contains("applicationId")) {
throw new IOException(
"Unable to find applicationId in "
+ getModule().getRootFile().getName()
+ "/build.gradle file");
} else if (content.contains("applicationId") && content.contains("namespace")) {
return packageName;
} else if (content.contains("applicationId") && !content.contains("namespace")) {
packageName = getModule().getApplicationId();
} else {
throw new IOException(
"Unable to find namespace or applicationId in "
+ getModule().getRootFile().getName()
+ "/build.gradle file");
}
} else {
throw new IOException(
"Unable to read " + getModule().getRootFile().getName() + "/build.gradle file");
}
return packageName;
}
private String parseString(File gradle) {
if (gradle != null && gradle.exists()) {
try {
String readString = FileUtils.readFileToString(gradle, Charset.defaultCharset());
if (readString != null && !readString.isEmpty()) {
return readString;
}
} catch (IOException e) {
// handle the exception here, if needed
}
}
return null;
}
}
| 8,852 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaLibraryBuilder.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/builder/JavaLibraryBuilder.java | package com.tyron.builder.compiler.builder;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.BuilderImpl;
import com.tyron.builder.compiler.CleanTask;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.compiler.incremental.java.IncrementalJavaFormatTask;
import com.tyron.builder.compiler.incremental.java.IncrementalJavaTask;
import com.tyron.builder.compiler.incremental.kotlin.IncrementalKotlinCompiler;
import com.tyron.builder.compiler.incremental.kotlin.IncrementalKotlinFormatTask;
import com.tyron.builder.compiler.incremental.resource.IncrementalAssembleLibraryTask;
import com.tyron.builder.compiler.jar.BuildJarTask;
import com.tyron.builder.compiler.java.CheckLibrariesTask;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.util.ArrayList;
import java.util.List;
public class JavaLibraryBuilder extends BuilderImpl<AndroidModule> {
public JavaLibraryBuilder(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public List<Task<? super AndroidModule>> getTasks(BuildType type) {
AndroidModule module = getModule();
ILogger logger = getLogger();
List<Task<? super AndroidModule>> tasks = new ArrayList<>();
tasks.add(new CleanTask(getProject(), module, logger));
tasks.add(new IncrementalKotlinFormatTask(getProject(), module, logger));
tasks.add(new IncrementalJavaFormatTask(getProject(), module, logger));
tasks.add(new CheckLibrariesTask(getProject(), module, getLogger()));
tasks.add(new IncrementalAssembleLibraryTask(getProject(), module, getLogger()));
tasks.add(new IncrementalKotlinCompiler(getProject(), module, logger));
tasks.add(new IncrementalJavaTask(getProject(), module, getLogger()));
tasks.add(new BuildJarTask(getProject(), module, getLogger()));
return tasks;
}
}
| 1,953 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaApplicationBuilder.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/builder/JavaApplicationBuilder.java | package com.tyron.builder.compiler.builder;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.BuilderImpl;
import com.tyron.builder.compiler.CleanTask;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.compiler.apk.PackageTask;
import com.tyron.builder.compiler.dex.R8Task;
import com.tyron.builder.compiler.incremental.dex.IncrementalD8Task;
import com.tyron.builder.compiler.incremental.java.IncrementalJavaFormatTask;
import com.tyron.builder.compiler.incremental.java.IncrementalJavaTask;
import com.tyron.builder.compiler.incremental.kotlin.IncrementalKotlinCompiler;
import com.tyron.builder.compiler.incremental.kotlin.IncrementalKotlinFormatTask;
import com.tyron.builder.compiler.incremental.resource.IncrementalAssembleLibraryTask;
import com.tyron.builder.compiler.java.CheckLibrariesTask;
import com.tyron.builder.compiler.java.RunTask;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.json.JSONObject;
public class JavaApplicationBuilder extends BuilderImpl<AndroidModule> {
public JavaApplicationBuilder(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public List<Task<? super AndroidModule>> getTasks(BuildType type) {
AndroidModule module = getModule();
ILogger logger = getLogger();
List<Task<? super AndroidModule>> tasks = new ArrayList<>();
tasks.add(new CleanTask(getProject(), module, logger));
tasks.add(new IncrementalKotlinFormatTask(getProject(), module, logger));
tasks.add(new IncrementalJavaFormatTask(getProject(), module, logger));
tasks.add(new CheckLibrariesTask(getProject(), module, getLogger()));
try {
File buildSettings =
new File(
getProject().getRootFile(),
".idea/" + getProject().getRootName() + "_compiler_settings.json");
String content = new String(Files.readAllBytes(Paths.get(buildSettings.getAbsolutePath())));
JSONObject buildSettingsJson = new JSONObject(content);
boolean isDexLibrariesOnPrebuild =
Optional.ofNullable(buildSettingsJson.optJSONObject("dex"))
.map(json -> json.optString("isDexLibrariesOnPrebuild", "false"))
.map(Boolean::parseBoolean)
.orElse(false);
if (isDexLibrariesOnPrebuild) {
tasks.add(new IncrementalD8Task(getProject(), module, logger));
}
} catch (Exception e) {
}
tasks.add(new IncrementalAssembleLibraryTask(getProject(), module, getLogger()));
tasks.add(new IncrementalKotlinCompiler(getProject(), module, logger));
tasks.add(new IncrementalJavaTask(getProject(), module, getLogger()));
if (type == BuildType.RELEASE) {
tasks.add(new R8Task(getProject(), module, getLogger()));
} else {
tasks.add(new IncrementalD8Task(getProject(), module, getLogger()));
}
tasks.add(new PackageTask(getProject(), module, getLogger()));
tasks.add(new RunTask(getProject(), module, getLogger()));
return tasks;
}
}
| 3,276 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AndroidLibraryBuilder.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/builder/AndroidLibraryBuilder.java | package com.tyron.builder.compiler.builder;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.BuilderImpl;
import com.tyron.builder.compiler.CleanTask;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.compiler.aar.BuildAarTask;
import com.tyron.builder.compiler.buildconfig.GenerateDebugBuildConfigTask;
import com.tyron.builder.compiler.buildconfig.GenerateReleaseBuildConfigTask;
import com.tyron.builder.compiler.incremental.java.IncrementalJavaFormatTask;
import com.tyron.builder.compiler.incremental.java.IncrementalJavaTask;
import com.tyron.builder.compiler.incremental.kotlin.IncrementalKotlinCompiler;
import com.tyron.builder.compiler.incremental.kotlin.IncrementalKotlinFormatTask;
import com.tyron.builder.compiler.incremental.resource.IncrementalAapt2Task;
import com.tyron.builder.compiler.incremental.resource.IncrementalAssembleLibraryTask;
import com.tyron.builder.compiler.java.CheckLibrariesTask;
import com.tyron.builder.compiler.manifest.ManifestMergeTask;
import com.tyron.builder.compiler.symbol.MergeSymbolsTask;
import com.tyron.builder.compiler.viewbinding.GenerateViewBindingTask;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import java.util.ArrayList;
import java.util.List;
public class AndroidLibraryBuilder extends BuilderImpl<AndroidModule> {
public AndroidLibraryBuilder(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public List<Task<? super AndroidModule>> getTasks(BuildType type) {
AndroidModule module = getModule();
ILogger logger = getLogger();
List<Task<? super AndroidModule>> tasks = new ArrayList<>();
tasks.add(new CleanTask(getProject(), module, logger));
tasks.add(new IncrementalKotlinFormatTask(getProject(), module, logger));
tasks.add(new IncrementalJavaFormatTask(getProject(), module, logger));
tasks.add(new CheckLibrariesTask(getProject(), module, getLogger()));
tasks.add(new IncrementalAssembleLibraryTask(getProject(), module, getLogger()));
tasks.add(new ManifestMergeTask(getProject(), module, logger));
if (type == BuildType.DEBUG) {
tasks.add(new GenerateDebugBuildConfigTask(getProject(), module, logger));
} else {
tasks.add(new GenerateReleaseBuildConfigTask(getProject(), module, logger));
}
tasks.add(new IncrementalAapt2Task(getProject(), module, logger, false));
tasks.add(new GenerateViewBindingTask(getProject(), module, logger, true));
tasks.add(new MergeSymbolsTask(getProject(), module, logger));
tasks.add(new IncrementalKotlinCompiler(getProject(), module, logger));
tasks.add(new IncrementalJavaTask(getProject(), module, getLogger()));
tasks.add(new BuildAarTask(getProject(), module, getLogger()));
return tasks;
}
}
| 2,894 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AAPT2Compiler.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/compiler/resource/AAPT2Compiler.java | package com.tyron.builder.compiler.resource;
import android.util.Log;
import com.android.tools.aapt2.Aapt2Jni;
import com.tyron.builder.BuildModule;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.log.LogUtils;
import com.tyron.builder.model.DiagnosticWrapper;
import com.tyron.builder.model.Project;
import com.tyron.builder.parser.FileManager;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
public class AAPT2Compiler {
private static final Pattern MANIFEST_PACKAGE =
Pattern.compile("\\s*(package)\\s*(=)\\s*(\")([a-zA-Z0-9.]+)(\")");
private static final String TAG = AAPT2Compiler.class.getSimpleName();
private final Project mProject;
private final ILogger mLogger;
public AAPT2Compiler(ILogger log, Project project) {
mLogger = log;
mProject = project;
}
public void run() throws IOException, CompilationFailedException {
long start = System.currentTimeMillis();
compileProject();
link();
Log.d(TAG, "Resource compilation took " + (System.currentTimeMillis() - start) + " ms");
}
private void compileProject() throws IOException, CompilationFailedException {
mLogger.debug("Compiling project resources.");
FileManager.deleteDir(getOutputPath());
FileManager.deleteDir(new File(mProject.getBuildDirectory(), "gen"));
List<String> args = new ArrayList<>();
args.add("--dir");
args.add(mProject.getResourceDirectory().getAbsolutePath());
args.add("-o");
args.add(createNewFile(getOutputPath(), "project.zip").getAbsolutePath());
int compile = Aapt2Jni.compile(args);
List<DiagnosticWrapper> logs = Aapt2Jni.getLogs();
LogUtils.log(logs, mLogger);
if (compile != 0) {
throw new CompilationFailedException("Compilation failed, check logs for more details.");
}
compileLibraries();
}
private void compileLibraries() throws IOException, CompilationFailedException {
mLogger.debug("Compiling libraries.");
for (File file : mProject.getLibraries()) {
File parent = file.getParentFile();
if (parent == null) {
throw new IOException("Library folder doesn't exist");
}
File resFolder = new File(parent, "res");
if (!resFolder.exists() || !resFolder.isDirectory()) {
continue;
}
Log.d(TAG, "Compiling library " + parent.getName());
List<String> args = new ArrayList<>();
args.add(getBinary().getAbsolutePath());
args.add("compile");
args.add("--dir");
args.add(resFolder.getAbsolutePath());
args.add("-o");
args.add(createNewFile(getOutputPath(), parent.getName() + ".zip").getAbsolutePath());
int compile = Aapt2Jni.compile(args);
List<DiagnosticWrapper> logs = Aapt2Jni.getLogs();
LogUtils.log(logs, mLogger);
if (compile != 0) {
throw new CompilationFailedException("Compilation failed, check logs for more details.");
}
}
}
private void link() throws IOException, CompilationFailedException {
mLogger.debug("Linking resources");
List<String> args = new ArrayList<>();
args.add("-I");
args.add(BuildModule.getAndroidJar().getAbsolutePath());
args.add("--allow-reserved-package-id");
args.add("--no-version-vectors");
args.add("--no-version-transitions");
args.add("--auto-add-overlay");
args.add("--min-sdk-version");
args.add(String.valueOf(mProject.getMinSdk()));
args.add("--target-sdk-version");
args.add(String.valueOf(mProject.getTargetSdk()));
File[] resources = getOutputPath().listFiles();
if (resources != null) {
for (File resource : resources) {
if (resource.isDirectory()) {
continue;
}
if (!resource.getName().endsWith(".zip")) {
continue;
}
args.add("-R");
args.add(resource.getAbsolutePath());
}
}
args.add("--java");
File gen = new File(mProject.getBuildDirectory(), "gen");
if (!gen.exists()) {
if (!gen.mkdirs()) {
throw new CompilationFailedException("Failed to create gen folder");
}
}
args.add(gen.getAbsolutePath());
args.add("--manifest");
args.add(mProject.getManifestFile().getAbsolutePath());
args.add("-o");
args.add(getOutputPath().getParent() + "/generated.apk.res");
args.add("--output-text-symbols");
File file = new File(getOutputPath(), "R.txt");
Files.deleteIfExists(file.toPath());
if (!file.createNewFile()) {
throw new IOException("Unable to create R.txt file");
}
args.add(file.getAbsolutePath());
int compile = Aapt2Jni.link(args);
List<DiagnosticWrapper> logs = Aapt2Jni.getLogs();
LogUtils.log(logs, mLogger);
if (compile != 0) {
throw new CompilationFailedException("Compilation failed, check logs for more details.");
}
}
private File getOutputPath() throws IOException {
File file = new File(mProject.getBuildDirectory(), "bin/res");
if (!file.exists()) {
if (!file.mkdirs()) {
throw new IOException("Failed to get resource directory");
}
}
return file;
}
private File createNewFile(File parent, String name) throws IOException {
File createdFile = new File(parent, name);
if (!parent.exists()) {
if (!parent.mkdirs()) {
throw new IOException("Unable to create directories");
}
}
if (!createdFile.createNewFile()) {
throw new IOException("Unable to create file " + name);
}
return createdFile;
}
/**
* Retrieves the package names of libraries of has a resource file
*
* @return list of package names in a form of string separated by ":" for use with AAPT2 directly
*/
private String getPackageNames() {
StringBuilder builder = new StringBuilder();
// getLibraries return list of classes.jar, get its parent
for (File library : mProject.getLibraries()) {
File parent = library.getParentFile();
String packageName = getPackageName(parent);
if (packageName != null) {
builder.append(packageName);
builder.append(":");
}
}
return builder.toString();
}
/**
* Retrieves the package name of a manifest (.xml) file
*
* @return null if an exception occurred or cannot be determined.
*/
public static String getPackageName(File library) {
String manifestString;
try {
manifestString = FileUtils.readFileToString(library, Charset.defaultCharset());
} catch (IOException e) {
return null;
}
Matcher matcher = MANIFEST_PACKAGE.matcher(manifestString);
if (matcher.find()) {
return matcher.group(4);
}
return null;
}
private static File getBinary() throws IOException {
File check =
new File(BuildModule.getContext().getApplicationInfo().nativeLibraryDir, "libaapt2.so");
if (check.exists()) {
return check;
}
throw new IOException("AAPT2 Binary not found");
}
}
| 7,223 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
LogUtils.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/log/LogUtils.java | package com.tyron.builder.log;
import com.tyron.builder.model.DiagnosticWrapper;
import java.util.List;
public class LogUtils {
public static void log(List<DiagnosticWrapper> logs, ILogger logger) {
for (DiagnosticWrapper log : logs) {
log(log, logger);
}
}
public static void log(DiagnosticWrapper log, ILogger logger) {
switch (log.getKind()) {
case ERROR:
logger.error(log);
break;
case MANDATORY_WARNING:
case WARNING:
logger.warning(log);
break;
case OTHER:
case NOTE:
logger.info(log);
break;
}
}
}
| 617 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CrashlyticsTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/crashlytics/CrashlyticsTask.java | package com.tyron.builder.crashlytics;
import android.util.Log;
import com.tyron.builder.compiler.BuildType;
import com.tyron.builder.compiler.Task;
import com.tyron.builder.compiler.manifest.resources.ResourceType;
import com.tyron.builder.exception.CompilationFailedException;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.xml.completion.repository.Repository;
import com.tyron.xml.completion.repository.ResourceItem;
import com.tyron.xml.completion.repository.api.ResourceNamespace;
import com.tyron.xml.completion.repository.api.ResourceReference;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.intellij.lang.annotations.Language;
/** Task to inject crashlytics build id to the resource directory */
public class CrashlyticsTask extends Task<AndroidModule> {
private static final String TAG = "crashlytics";
private static final String LEGACY_MAPPING_FILE_ID_RESOURCE_NAME =
"com_crashlytics_android_build_id";
private static final String CORE_CLASS =
"com.google.firebase.crashlytics.internal.common.CrashlyticsCore";
private static final String CRASHLYTICS_RESOURCE_FILE = "code_assist_crashlytics__.xml";
private static final CharSequence CRASHLYTICS_BUILD_ID = "code_assist_crashlytics_task_0282";
private static final String XML_REPOSITORY_CLASS = "com.tyron.completion.xml.XmlRepository";
private boolean mContainsCrashlytics;
public CrashlyticsTask(Project project, AndroidModule module, ILogger logger) {
super(project, module, logger);
}
@Override
public String getName() {
return TAG;
}
@Override
public void prepare(BuildType type) throws IOException {
mContainsCrashlytics = getModule().getAllClasses().contains(CORE_CLASS);
}
@Override
public void run() throws IOException, CompilationFailedException {
if (!mContainsCrashlytics) {
return;
}
Repository repository = getRepository(getProject(), getModule());
if (repository == null) {
Log.w(TAG, "Unable to get repository.");
return;
}
ResourceNamespace namespace = repository.getNamespace();
ResourceReference resourceReference =
new ResourceReference(namespace, ResourceType.STRING, LEGACY_MAPPING_FILE_ID_RESOURCE_NAME);
List<ResourceItem> resources = repository.getResources(resourceReference);
if (!resources.isEmpty()) {
return;
}
File valuesDir = new File(getModule().getAndroidResourcesDirectory(), "values");
if (!valuesDir.exists() && !valuesDir.mkdirs()) {
throw new IOException("Unable to create values directory");
}
File resFile = new File(valuesDir, CRASHLYTICS_RESOURCE_FILE);
if (!resFile.exists() && !resFile.createNewFile()) {
throw new IOException("Unable to create crashlytics resource file");
}
@Language("XML")
String contents =
"<resources>\n" + " <string name=\"$name\">$value</string>\n" + "</resources>";
contents = contents.replace("$name", LEGACY_MAPPING_FILE_ID_RESOURCE_NAME);
contents = contents.replace("$value", CRASHLYTICS_BUILD_ID);
FileUtils.writeStringToFile(resFile, contents, StandardCharsets.UTF_8);
}
public static Repository getRepository(Project project, AndroidModule module) {
try {
Class<?> clazz = Class.forName(XML_REPOSITORY_CLASS);
Method method = clazz.getDeclaredMethod("getRepository", Project.class, AndroidModule.class);
Object invoke = method.invoke(null, project, module);
Method getRepository = clazz.getDeclaredMethod("getRepository");
Object invoke1 = getRepository.invoke(invoke);
if (invoke1 instanceof Repository) {
return ((Repository) invoke1);
}
return null;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
}
| 4,000 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompilationFailedException.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/exception/CompilationFailedException.java | package com.tyron.builder.exception;
public class CompilationFailedException extends Exception {
public CompilationFailedException(String message, Throwable t) {
super(message, t);
}
public CompilationFailedException(Exception exception) {
super(exception);
}
public CompilationFailedException(String message) {
super(message);
}
}
| 360 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
SourceFileObject.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/model/SourceFileObject.java | package com.tyron.builder.model;
import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
import com.tyron.builder.project.api.JavaModule;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.Optional;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import org.apache.commons.io.FileUtils;
@SuppressLint("NewApi")
public class SourceFileObject extends SimpleJavaFileObject {
public Path mFile;
private final Instant modified;
private final String mContents;
private final JavaModule mProject;
public SourceFileObject(Path file) {
this(file, null, null, null);
}
public SourceFileObject(Path file, JavaModule project) {
this(file, null, null, project);
}
public SourceFileObject(Path file, JavaModule project, Instant modified) {
this(file, null, modified, project);
}
public SourceFileObject(Path file, String contents, Instant modified) {
this(file, contents, modified, null);
}
public SourceFileObject(Path file, String contents, Instant modified, JavaModule project) {
super(file.toUri(), JavaFileObject.Kind.SOURCE);
mContents = contents;
mFile = file;
this.modified = modified;
mProject = project;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
if (mProject != null) {
Optional<CharSequence> fileContent = mProject.getFileManager().getFileContent(mFile.toFile());
if (fileContent.isPresent()) {
return replaceContents(String.valueOf(fileContent.get()));
}
}
if (mContents != null) {
return replaceContents(mContents);
}
try {
String s = FileUtils.readFileToString(mFile.toFile(), Charset.defaultCharset());
return replaceContents(s);
} catch (IOException e) {
return null;
}
}
/**
* By default, the java compiler treats tabs as 8 spaces. A work around for this is to replace the
* tabs with the number of space of tabs from the editor
*/
private String replaceContents(String contents) {
return contents;
}
@Override
public Kind getKind() {
String name = mFile.getFileName().toString();
return kindFromExtension(name);
}
private static Kind kindFromExtension(String name) {
for (Kind candidate : Kind.values()) {
if (name.endsWith(candidate.extension)) {
return candidate;
}
}
return null;
}
@Override
public boolean isNameCompatible(String simpleName, Kind kind) {
return mFile.getFileName().toString().equals(simpleName + kind.extension);
}
@Override
public URI toUri() {
return mFile.toUri();
}
@Override
public long getLastModified() {
if (modified == null) {
try {
return Files.getLastModifiedTime(mFile).toMillis();
} catch (IOException e) {
return Instant.EPOCH.toEpochMilli();
}
}
return modified.toEpochMilli();
}
@NonNull
@Override
public String toString() {
return mFile.toString();
}
@Override
public boolean equals(Object o) {
if (getClass() != o.getClass()) return false;
SourceFileObject that = (SourceFileObject) o;
return this.mFile.equals(that.mFile);
}
@Override
public int hashCode() {
return mFile.hashCode();
}
}
| 3,394 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
Project.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/tyron/builder/model/Project.java | package com.tyron.builder.model;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.tyron.builder.BuildModule;
import com.tyron.builder.compiler.manifest.xml.AndroidManifestParser;
import com.tyron.builder.compiler.manifest.xml.ManifestData;
import com.tyron.builder.parser.FileManager;
import com.tyron.common.util.Decompress;
import com.tyron.common.util.StringSearch;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.lang.model.SourceVersion;
/**
* Class for storing project data, directories and files
*
* @deprecated legacy code, use {@link com.tyron.builder.project.Project} instead.
*/
@Deprecated
public class Project {
public final File mRoot;
public Map<String, File> javaFiles = new HashMap<>();
private final Map<String, File> kotlinFiles = new HashMap<>();
private final Set<File> libraries = new HashSet<>();
private final Map<String, File> RJavaFiles = new HashMap<>();
private final File mAssetsDir;
private final File mNativeLibsDir;
private final FileManager mFileManager;
private ManifestData mManifestData;
private ModuleSettings mSettings;
/** Creates a project object from specified root */
public Project(File root) {
mRoot = root;
mAssetsDir = new File(root, "app/src/main/assets");
mNativeLibsDir = new File(root, "app/src/main/jniLibs");
mFileManager = new FileManager();
}
@VisibleForTesting
public Project(FileManager manager) {
try {
mAssetsDir = File.createTempFile("assets", "");
mNativeLibsDir = new File("jniLibs");
mRoot = mNativeLibsDir.getParentFile();
mFileManager = manager;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public ModuleSettings getSettings() {
mSettings.refresh();
return mSettings;
}
public FileManager getFileManager() {
return mFileManager;
}
public String getPackageName() {
return mManifestData.getPackage();
}
public String getName() {
return mRoot.getName();
}
public Map<String, File> getJavaFiles() {
if (javaFiles.isEmpty()) {
findJavaFiles(getJavaDirectory());
}
return javaFiles;
}
public Map<String, File> getKotlinFiles() {
if (kotlinFiles.isEmpty()) {
findKotlinFiles(getJavaDirectory());
findKotlinFiles(getKotlinDirectory());
}
return kotlinFiles;
}
private void searchRJavaFiles(File root) {
File[] files = root.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
searchRJavaFiles(file);
} else {
String packageName = StringSearch.packageName(file);
if (!packageName.isEmpty()) {
packageName =
packageName + "." + file.getName().substring(0, file.getName().lastIndexOf("."));
RJavaFiles.put(packageName, file);
}
}
}
}
}
public Map<String, File> getRJavaFiles() {
if (RJavaFiles.isEmpty()) {
searchRJavaFiles(new File(getBuildDirectory(), "gen"));
}
return RJavaFiles;
}
public void clearRJavaFiles() {
RJavaFiles.clear();
}
public Set<File> getLibraries() {
if (libraries.isEmpty()) {
searchLibraries();
}
return libraries;
}
private void findKotlinFiles(File file) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
if (child.isDirectory()) {
findKotlinFiles(child);
} else {
if (child.getName().endsWith(".kt")) {
String packageName = StringSearch.packageName(child);
if (packageName.isEmpty()) {
Log.d("Error package empty", child.getAbsolutePath());
} else {
String name = packageName + "." + child.getName().replace(".kt", "");
Log.d("PROJECT FIND KOTLIN", "Found " + name);
kotlinFiles.put(name, child);
}
}
}
}
}
}
public void searchLibraries() {
libraries.clear();
File libPath = new File(getBuildDirectory(), "libs");
File[] files = libPath.listFiles();
if (files != null) {
for (File lib : files) {
if (lib.isDirectory()) {
File check = new File(lib, "classes.jar");
if (check.exists()) {
libraries.add(check);
}
}
}
}
}
private void findJavaFiles(File file) {
File[] files = file.listFiles();
if (files != null) {
for (File child : files) {
if (child.isDirectory()) {
findJavaFiles(child);
} else {
if (child.getName().endsWith(".java")) {
String packageName = StringSearch.packageName(child);
Log.d("PROJECT FIND JAVA", "Found " + child.getAbsolutePath());
if (packageName.isEmpty()) {
Log.d("Error package empty", child.getAbsolutePath());
} else {
if (SourceVersion.isName(packageName + "." + child.getName().replace(".java", ""))) {
javaFiles.put(packageName + "." + child.getName().replace(".java", ""), child);
}
}
}
}
}
}
}
/**
* Clears all the cached files stored in this project, the next time ths project is opened, it
* will get loaded again
*/
public void clear() {
RJavaFiles.clear();
libraries.clear();
javaFiles.clear();
kotlinFiles.clear();
}
/**
* Used to check if this project contains the required directories such as app/src/main/java,
* resources and others
*/
public boolean isValidProject() {
File check = new File(mRoot, "app/src/main/java");
if (!check.exists()) {
return false;
}
return getResourceDirectory().exists();
}
/**
* Creates a new project configured at mRoot, returns true if the project has been created, false
* if not.
*/
public boolean create() {
// this project already exists
if (isValidProject()) {
return false;
}
File java = getJavaDirectory();
if (!java.mkdirs()) {
return false;
}
if (!getResourceDirectory().mkdirs()) {
return false;
}
Decompress.unzipFromAssets(
BuildModule.getContext(), "test_project.zip", java.getAbsolutePath());
if (!getLibraryDirectory().mkdirs()) {
return false;
}
return getBuildDirectory().mkdirs();
}
public void open() throws IOException {
mFileManager.openProject(this);
mManifestData = AndroidManifestParser.parse(getManifestFile().toPath());
if (!getConfigFile().exists() && !getConfigFile().createNewFile()) {
throw new IOException("Unable to create config file");
}
mSettings = new ModuleSettings(getConfigFile());
}
@VisibleForTesting
public void createForTesting() {
Decompress.unzipFromAssets(
BuildModule.getContext(), "project_unit_test.zip", mRoot.getAbsolutePath());
}
public int getMinSdk() {
return mManifestData.getMinSdkVersion();
}
public int getTargetSdk() {
return mManifestData.getTargetSdkVersion();
}
public File getResourceDirectory() {
return new File(mRoot, "app/src/main/res");
}
public File getJavaDirectory() {
return new File(mRoot, "app/src/main/java");
}
public File getKotlinDirectory() {
return new File(mRoot, "app/src/main/kotlin");
}
public File getLibraryDirectory() {
return new File(mRoot, "app/libs");
}
public File getBuildDirectory() {
return new File(mRoot, "app/build");
}
public File getManifestFile() {
return new File(mRoot, "app/src/main/AndroidManifest.xml");
}
public File getAssetsDirectory() {
return mAssetsDir;
}
public File getNativeLibsDirectory() {
return mNativeLibsDir;
}
public File getConfigFile() {
return new File(mRoot, "app_config.json");
}
@Override
public int hashCode() {
return mRoot.hashCode();
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj instanceof Project) {
Project that = (Project) obj;
return this.mRoot.equals(that.mRoot);
}
return false;
}
}
| 8,294 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
Aapt2Jni.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/build-logic/src/main/java/com/android/tools/aapt2/Aapt2Jni.java | package com.android.tools.aapt2;
import androidx.annotation.VisibleForTesting;
import com.tyron.builder.BuildModule;
import com.tyron.builder.model.DiagnosticWrapper;
import com.tyron.common.util.BinaryExecutor;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.tools.Diagnostic;
import org.apache.commons.lang3.StringUtils;
public class Aapt2Jni {
private static final Pattern DIAGNOSTIC_PATTERN = Pattern.compile("(.*?):(\\d+): (.*?): (.+)");
private static final Pattern DIAGNOSTIC_PATTERN_NO_LINE =
Pattern.compile("(.*?): (.*?)" + ":" + " (.+)");
private static final Pattern ERROR_PATTERN_NO_LINE = Pattern.compile("(error:) (.*?)");
private static final int LOG_LEVEL_ERROR = 3;
private static final int LOG_LEVEL_WARNING = 2;
private static final int LOG_LEVEL_INFO = 1;
private static final Aapt2Jni INSTANCE = new Aapt2Jni();
public static Aapt2Jni getInstance() {
return INSTANCE;
}
private String mFailureString;
private final List<DiagnosticWrapper> mDiagnostics = new ArrayList<>();
private Aapt2Jni() {}
private static int getLineNumber(String number) {
try {
return Integer.parseInt(number);
} catch (NumberFormatException e) {
return 0;
}
}
private static int getLogLevel(String level) {
if (level == null) {
return 1;
}
switch (level) {
case "error":
return 3;
case "warning":
return 2;
default:
case "info":
return 1;
}
}
/**
* Called by AAPT2 through JNI.
*
* @param level log level (3 = error, 2 = warning, 1 = info)
* @param path path to the file with the issue
* @param line line number of the issue
* @param message issue message
*/
@SuppressWarnings({"unused", "SameParameterValue"})
private void log(int level, String path, long line, String message) {
DiagnosticWrapper wrapper = new DiagnosticWrapper();
switch (level) {
case LOG_LEVEL_ERROR:
wrapper.setKind(Diagnostic.Kind.ERROR);
break;
case LOG_LEVEL_WARNING:
wrapper.setKind(Diagnostic.Kind.WARNING);
break;
case LOG_LEVEL_INFO:
wrapper.setKind(Diagnostic.Kind.NOTE);
break;
default:
wrapper.setKind(Diagnostic.Kind.OTHER);
break;
}
if (path != null) {
wrapper.setSource(new File(path));
}
if (line != -1) {
wrapper.setLineNumber(line);
wrapper.setEndLine((int) line);
wrapper.setStartLine((int) line);
}
wrapper.setMessage(message);
mDiagnostics.add(wrapper);
}
private void clearLogs() {
mDiagnostics.clear();
}
/**
* Compile resources with Aapt2
*
* @param args the arguments to pass to aapt2
* @return exit code, non zero if theres an error
*/
public static int compile(List<String> args) {
Aapt2Jni instance = Aapt2Jni.getInstance();
instance.clearLogs();
// aapt2 has failed to load, fail early
if (instance.mFailureString != null) {
instance.log(LOG_LEVEL_ERROR, null, -1, instance.mFailureString);
return -1;
}
args.add(0, "compile");
args.add(0, getBinary());
return executeBinary(args, instance);
}
public static int link(List<String> args) {
Aapt2Jni instance = Aapt2Jni.getInstance();
instance.clearLogs();
// aapt2 has failed to load, fail early
if (instance.mFailureString != null) {
instance.log(LOG_LEVEL_ERROR, null, -1, instance.mFailureString);
return -1;
}
args.add(0, "link");
args.add(0, getBinary());
return executeBinary(args, instance);
}
private static File sAapt2Binary;
@VisibleForTesting
public static void setAapt2Binary(File file) {
sAapt2Binary = file;
}
private static String getBinary() {
if (sAapt2Binary != null) {
return sAapt2Binary.getAbsolutePath();
}
return BuildModule.getContext().getApplicationInfo().nativeLibraryDir + "/libaapt2.so";
}
private static int executeBinary(List<String> args, Aapt2Jni logger) {
BinaryExecutor binaryExecutor = new BinaryExecutor();
binaryExecutor.setCommands(args);
String execute = binaryExecutor.execute();
String[] lines = execute.split("\n");
for (String line : lines) {
if (StringUtils.isEmpty(line)) {
continue;
}
Matcher matcher = DIAGNOSTIC_PATTERN.matcher(line);
Matcher m = DIAGNOSTIC_PATTERN_NO_LINE.matcher(line);
Matcher error = ERROR_PATTERN_NO_LINE.matcher(line);
String path;
String lineNumber;
String level;
String message;
if (matcher.find()) {
path = matcher.group(1);
lineNumber = matcher.group(2);
level = matcher.group(3);
message = matcher.group(4);
} else if (m.find()) {
path = m.group(1);
lineNumber = "-1";
level = m.group(2);
message = m.group(3);
} else {
String trim = line.trim();
if (trim.startsWith("error")) {
level = "error";
} else {
level = "info";
}
path = "";
lineNumber = "-1";
message = line;
}
logger.log(getLogLevel(level), path, getLineNumber(lineNumber), message);
}
return logger.mDiagnostics.stream().anyMatch(it -> it.getKind() == Diagnostic.Kind.ERROR)
? 1
: 0;
}
public static List<DiagnosticWrapper> getLogs() {
return getInstance().mDiagnostics;
}
}
| 5,544 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
MethodSpec.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/MethodSpec.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import static com.squareup.javapoet.Util.checkState;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openjdk.javax.lang.model.SourceVersion;
import org.openjdk.javax.lang.model.element.ExecutableElement;
import org.openjdk.javax.lang.model.element.Modifier;
import org.openjdk.javax.lang.model.element.TypeParameterElement;
import org.openjdk.javax.lang.model.type.DeclaredType;
import org.openjdk.javax.lang.model.type.ExecutableType;
import org.openjdk.javax.lang.model.type.TypeMirror;
import org.openjdk.javax.lang.model.type.TypeVariable;
import org.openjdk.javax.lang.model.util.Types;
/** A generated constructor or method declaration. */
public final class MethodSpec {
static final String CONSTRUCTOR = "<init>";
public final String name;
public final CodeBlock javadoc;
public final List<AnnotationSpec> annotations;
public final Set<Modifier> modifiers;
public final List<TypeVariableName> typeVariables;
public final TypeName returnType;
public final List<ParameterSpec> parameters;
public final boolean varargs;
public final List<TypeName> exceptions;
public final CodeBlock code;
public final CodeBlock defaultValue;
private MethodSpec(Builder builder) {
CodeBlock code = builder.code.build();
checkArgument(
code.isEmpty() || !builder.modifiers.contains(Modifier.ABSTRACT),
"abstract method %s cannot have code",
builder.name);
checkArgument(
!builder.varargs || lastParameterIsArray(builder.parameters),
"last parameter of varargs method %s must be an array",
builder.name);
this.name = checkNotNull(builder.name, "name == null");
this.javadoc = builder.javadoc.build();
this.annotations = Util.immutableList(builder.annotations);
this.modifiers = Util.immutableSet(builder.modifiers);
this.typeVariables = Util.immutableList(builder.typeVariables);
this.returnType = builder.returnType;
this.parameters = Util.immutableList(builder.parameters);
this.varargs = builder.varargs;
this.exceptions = Util.immutableList(builder.exceptions);
this.defaultValue = builder.defaultValue;
this.code = code;
}
private boolean lastParameterIsArray(List<ParameterSpec> parameters) {
return !parameters.isEmpty()
&& TypeName.arrayComponent(parameters.get(parameters.size() - 1).type) != null;
}
void emit(CodeWriter codeWriter, String enclosingName, Set<Modifier> implicitModifiers)
throws IOException {
codeWriter.emitJavadoc(javadoc);
codeWriter.emitAnnotations(annotations, false);
codeWriter.emitModifiers(modifiers, implicitModifiers);
if (!typeVariables.isEmpty()) {
codeWriter.emitTypeVariables(typeVariables);
codeWriter.emit(" ");
}
if (isConstructor()) {
codeWriter.emit("$L($Z", enclosingName);
} else {
codeWriter.emit("$T $L($Z", returnType, name);
}
boolean firstParameter = true;
for (Iterator<ParameterSpec> i = parameters.iterator(); i.hasNext(); ) {
ParameterSpec parameter = i.next();
if (!firstParameter) codeWriter.emit(",").emitWrappingSpace();
parameter.emit(codeWriter, !i.hasNext() && varargs);
firstParameter = false;
}
codeWriter.emit(")");
if (defaultValue != null && !defaultValue.isEmpty()) {
codeWriter.emit(" default ");
codeWriter.emit(defaultValue);
}
if (!exceptions.isEmpty()) {
codeWriter.emitWrappingSpace().emit("throws");
boolean firstException = true;
for (TypeName exception : exceptions) {
if (!firstException) codeWriter.emit(",");
codeWriter.emitWrappingSpace().emit("$T", exception);
firstException = false;
}
}
if (hasModifier(Modifier.ABSTRACT)) {
codeWriter.emit(";\n");
} else if (hasModifier(Modifier.NATIVE)) {
// Code is allowed to support stuff like GWT JSNI.
codeWriter.emit(code);
codeWriter.emit(";\n");
} else {
codeWriter.emit(" {\n");
codeWriter.indent();
codeWriter.emit(code);
codeWriter.unindent();
codeWriter.emit("}\n");
}
}
public boolean hasModifier(Modifier modifier) {
return modifiers.contains(modifier);
}
public boolean isConstructor() {
return name.equals(CONSTRUCTOR);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
return toString().equals(o.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
try {
CodeWriter codeWriter = new CodeWriter(out);
emit(codeWriter, "Constructor", Collections.<Modifier>emptySet());
return out.toString();
} catch (IOException e) {
throw new AssertionError();
}
}
public static Builder methodBuilder(String name) {
return new Builder(name);
}
public static Builder constructorBuilder() {
return new Builder(CONSTRUCTOR);
}
/**
* Returns a new method spec builder that overrides {@code method}.
*
* <p>This will copy its visibility modifiers, type parameters, return type, name, parameters, and
* throws declarations. An {@link Override} annotation will be added.
*
* <p>Note that in JavaPoet 1.2 through 1.7 this method retained annotations from the method and
* parameters of the overridden method. Since JavaPoet 1.8 annotations must be added separately.
*/
public static Builder overriding(ExecutableElement method) {
checkNotNull(method, "method == null");
Set<Modifier> modifiers = method.getModifiers();
if (modifiers.contains(Modifier.PRIVATE)
|| modifiers.contains(Modifier.FINAL)
|| modifiers.contains(Modifier.STATIC)) {
throw new IllegalArgumentException("cannot override method with modifiers: " + modifiers);
}
String methodName = method.getSimpleName().toString();
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName);
methodBuilder.addAnnotation(Override.class);
modifiers = new LinkedHashSet<>(modifiers);
modifiers.remove(Modifier.ABSTRACT);
modifiers.remove(Util.DEFAULT); // LinkedHashSet permits null as element for Java 7
methodBuilder.addModifiers(modifiers);
for (TypeParameterElement typeParameterElement : method.getTypeParameters()) {
TypeVariable var = (TypeVariable) typeParameterElement.asType();
methodBuilder.addTypeVariable(TypeVariableName.get(var));
}
methodBuilder.returns(TypeName.get(method.getReturnType()));
methodBuilder.addParameters(ParameterSpec.parametersOf(method));
methodBuilder.varargs(method.isVarArgs());
for (TypeMirror thrownType : method.getThrownTypes()) {
methodBuilder.addException(TypeName.get(thrownType));
}
return methodBuilder;
}
/**
* Returns a new method spec builder that overrides {@code method} as a member of {@code
* enclosing}. This will resolve type parameters: for example overriding {@link
* Comparable#compareTo} in a type that implements {@code Comparable<Movie>}, the {@code T}
* parameter will be resolved to {@code Movie}.
*
* <p>This will copy its visibility modifiers, type parameters, return type, name, parameters, and
* throws declarations. An {@link Override} annotation will be added.
*
* <p>Note that in JavaPoet 1.2 through 1.7 this method retained annotations from the method and
* parameters of the overridden method. Since JavaPoet 1.8 annotations must be added separately.
*/
public static Builder overriding(ExecutableElement method, DeclaredType enclosing, Types types) {
ExecutableType executableType = (ExecutableType) types.asMemberOf(enclosing, method);
List<? extends TypeMirror> resolvedParameterTypes = executableType.getParameterTypes();
TypeMirror resolvedReturnType = executableType.getReturnType();
Builder builder = overriding(method);
builder.returns(TypeName.get(resolvedReturnType));
for (int i = 0, size = builder.parameters.size(); i < size; i++) {
ParameterSpec parameter = builder.parameters.get(i);
TypeName type = TypeName.get(resolvedParameterTypes.get(i));
builder.parameters.set(i, parameter.toBuilder(type, parameter.name).build());
}
return builder;
}
public Builder toBuilder() {
Builder builder = new Builder(name);
builder.javadoc.add(javadoc);
builder.annotations.addAll(annotations);
builder.modifiers.addAll(modifiers);
builder.typeVariables.addAll(typeVariables);
builder.returnType = returnType;
builder.parameters.addAll(parameters);
builder.exceptions.addAll(exceptions);
builder.code.add(code);
builder.varargs = varargs;
builder.defaultValue = defaultValue;
return builder;
}
public static final class Builder {
private final String name;
private final CodeBlock.Builder javadoc = CodeBlock.builder();
private final List<AnnotationSpec> annotations = new ArrayList<>();
private final List<Modifier> modifiers = new ArrayList<>();
private List<TypeVariableName> typeVariables = new ArrayList<>();
private TypeName returnType;
private final List<ParameterSpec> parameters = new ArrayList<>();
private final Set<TypeName> exceptions = new LinkedHashSet<>();
private final CodeBlock.Builder code = CodeBlock.builder();
private boolean varargs;
private CodeBlock defaultValue;
private Builder(String name) {
checkNotNull(name, "name == null");
checkArgument(
name.equals(CONSTRUCTOR) || SourceVersion.isName(name), "not a valid name: %s", name);
this.name = name;
this.returnType = name.equals(CONSTRUCTOR) ? null : TypeName.VOID;
}
public Builder addJavadoc(String format, Object... args) {
javadoc.add(format, args);
return this;
}
public Builder addJavadoc(CodeBlock block) {
javadoc.add(block);
return this;
}
public Builder addAnnotations(Iterable<AnnotationSpec> annotationSpecs) {
checkArgument(annotationSpecs != null, "annotationSpecs == null");
for (AnnotationSpec annotationSpec : annotationSpecs) {
this.annotations.add(annotationSpec);
}
return this;
}
public Builder addAnnotation(AnnotationSpec annotationSpec) {
this.annotations.add(annotationSpec);
return this;
}
public Builder addAnnotation(ClassName annotation) {
this.annotations.add(AnnotationSpec.builder(annotation).build());
return this;
}
public Builder addAnnotation(Class<?> annotation) {
return addAnnotation(ClassName.get(annotation));
}
public Builder addModifiers(Modifier... modifiers) {
checkNotNull(modifiers, "modifiers == null");
Collections.addAll(this.modifiers, modifiers);
return this;
}
public Builder addModifiers(Iterable<Modifier> modifiers) {
checkNotNull(modifiers, "modifiers == null");
for (Modifier modifier : modifiers) {
this.modifiers.add(modifier);
}
return this;
}
public Builder addTypeVariables(Iterable<TypeVariableName> typeVariables) {
checkArgument(typeVariables != null, "typeVariables == null");
for (TypeVariableName typeVariable : typeVariables) {
this.typeVariables.add(typeVariable);
}
return this;
}
public Builder addTypeVariable(TypeVariableName typeVariable) {
typeVariables.add(typeVariable);
return this;
}
public Builder returns(TypeName returnType) {
checkState(!name.equals(CONSTRUCTOR), "constructor cannot have return type.");
this.returnType = returnType;
return this;
}
public Builder returns(Type returnType) {
return returns(TypeName.get(returnType));
}
public Builder addParameters(Iterable<ParameterSpec> parameterSpecs) {
checkArgument(parameterSpecs != null, "parameterSpecs == null");
for (ParameterSpec parameterSpec : parameterSpecs) {
this.parameters.add(parameterSpec);
}
return this;
}
public Builder addParameter(ParameterSpec parameterSpec) {
this.parameters.add(parameterSpec);
return this;
}
public Builder addParameter(TypeName type, String name, Modifier... modifiers) {
return addParameter(ParameterSpec.builder(type, name, modifiers).build());
}
public Builder addParameter(Type type, String name, Modifier... modifiers) {
return addParameter(TypeName.get(type), name, modifiers);
}
public Builder varargs() {
return varargs(true);
}
public Builder varargs(boolean varargs) {
this.varargs = varargs;
return this;
}
public Builder addExceptions(Iterable<? extends TypeName> exceptions) {
checkArgument(exceptions != null, "exceptions == null");
for (TypeName exception : exceptions) {
this.exceptions.add(exception);
}
return this;
}
public Builder addException(TypeName exception) {
this.exceptions.add(exception);
return this;
}
public Builder addException(Type exception) {
return addException(TypeName.get(exception));
}
public Builder addCode(String format, Object... args) {
code.add(format, args);
return this;
}
public Builder addNamedCode(String format, Map<String, ?> args) {
code.addNamed(format, args);
return this;
}
public Builder addCode(CodeBlock codeBlock) {
code.add(codeBlock);
return this;
}
public Builder addComment(String format, Object... args) {
code.add("// " + format + "\n", args);
return this;
}
public Builder defaultValue(String format, Object... args) {
return defaultValue(CodeBlock.of(format, args));
}
public Builder defaultValue(CodeBlock codeBlock) {
checkState(this.defaultValue == null, "defaultValue was already set");
this.defaultValue = checkNotNull(codeBlock, "codeBlock == null");
return this;
}
/**
* @param controlFlow the control flow construct and its code, such as "if (foo == 5)".
* Shouldn't contain braces or newline characters.
*/
public Builder beginControlFlow(String controlFlow, Object... args) {
code.beginControlFlow(controlFlow, args);
return this;
}
/**
* @param controlFlow the control flow construct and its code, such as "else if (foo == 10)".
* Shouldn't contain braces or newline characters.
*/
public Builder nextControlFlow(String controlFlow, Object... args) {
code.nextControlFlow(controlFlow, args);
return this;
}
public Builder endControlFlow() {
code.endControlFlow();
return this;
}
/**
* @param controlFlow the optional control flow construct and its code, such as "while(foo ==
* 20)". Only used for "do/while" control flows.
*/
public Builder endControlFlow(String controlFlow, Object... args) {
code.endControlFlow(controlFlow, args);
return this;
}
public Builder addStatement(String format, Object... args) {
code.addStatement(format, args);
return this;
}
public Builder addStatement(CodeBlock codeBlock) {
code.addStatement(codeBlock);
return this;
}
public MethodSpec build() {
return new MethodSpec(this);
}
}
}
| 16,428 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
TypeName.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/TypeName.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.openjdk.javax.lang.model.element.Modifier;
import org.openjdk.javax.lang.model.element.TypeElement;
import org.openjdk.javax.lang.model.element.TypeParameterElement;
import org.openjdk.javax.lang.model.type.ArrayType;
import org.openjdk.javax.lang.model.type.DeclaredType;
import org.openjdk.javax.lang.model.type.ErrorType;
import org.openjdk.javax.lang.model.type.NoType;
import org.openjdk.javax.lang.model.type.PrimitiveType;
import org.openjdk.javax.lang.model.type.TypeKind;
import org.openjdk.javax.lang.model.type.TypeMirror;
import org.openjdk.javax.lang.model.util.SimpleTypeVisitor7;
/**
* Any type in Java's type system, plus {@code void}. This class is an identifier for primitive
* types like {@code int} and raw reference types like {@code String} and {@code List}. It also
* identifies composite types like {@code char[]} and {@code Set<Long>}.
*
* <p>Type names are dumb identifiers only and do not model the values they name. For example, the
* type name for {@code java.lang.List} doesn't know about the {@code size()} method, the fact that
* lists are collections, or even that it accepts a single type parameter.
*
* <p>Instances of this class are immutable value objects that implement {@code equals()} and {@code
* hashCode()} properly.
*
* <h3>Referencing existing types</h3>
*
* <p>Primitives and void are constants that you can reference directly: see {@link #INT}, {@link
* #DOUBLE}, and {@link #VOID}.
*
* <p>In an annotation processor you can get a type name instance for a type mirror by calling
* {@link #get(TypeMirror)}. In reflection code, you can use {@link #get(Type)}.
*
* <h3>Defining new types</h3>
*
* <p>Create new reference types like {@code com.example.HelloWorld} with {@link
* ClassName#get(String, String, String...)}. To build composite types like {@code char[]} and
* {@code Set<Long>}, use the factory methods on {@link ArrayTypeName}, {@link
* ParameterizedTypeName}, {@link TypeVariableName}, and {@link WildcardTypeName}.
*/
public class TypeName {
public static final TypeName VOID = new TypeName("void");
public static final TypeName BOOLEAN = new TypeName("boolean");
public static final TypeName BYTE = new TypeName("byte");
public static final TypeName SHORT = new TypeName("short");
public static final TypeName INT = new TypeName("int");
public static final TypeName LONG = new TypeName("long");
public static final TypeName CHAR = new TypeName("char");
public static final TypeName FLOAT = new TypeName("float");
public static final TypeName DOUBLE = new TypeName("double");
public static final ClassName OBJECT = ClassName.get("java.lang", "Object");
private static final ClassName BOXED_VOID = ClassName.get("java.lang", "Void");
private static final ClassName BOXED_BOOLEAN = ClassName.get("java.lang", "Boolean");
private static final ClassName BOXED_BYTE = ClassName.get("java.lang", "Byte");
private static final ClassName BOXED_SHORT = ClassName.get("java.lang", "Short");
private static final ClassName BOXED_INT = ClassName.get("java.lang", "Integer");
private static final ClassName BOXED_LONG = ClassName.get("java.lang", "Long");
private static final ClassName BOXED_CHAR = ClassName.get("java.lang", "Character");
private static final ClassName BOXED_FLOAT = ClassName.get("java.lang", "Float");
private static final ClassName BOXED_DOUBLE = ClassName.get("java.lang", "Double");
/** The name of this type if it is a keyword, or null. */
private final String keyword;
public final List<AnnotationSpec> annotations;
/** Lazily-initialized toString of this type name. */
private String cachedString;
private TypeName(String keyword) {
this(keyword, new ArrayList<AnnotationSpec>());
}
private TypeName(String keyword, List<AnnotationSpec> annotations) {
this.keyword = keyword;
this.annotations = Util.immutableList(annotations);
}
// Package-private constructor to prevent third-party subclasses.
TypeName(List<AnnotationSpec> annotations) {
this(null, annotations);
}
public final TypeName annotated(AnnotationSpec... annotations) {
return annotated(Arrays.asList(annotations));
}
public TypeName annotated(List<AnnotationSpec> annotations) {
Util.checkNotNull(annotations, "annotations == null");
return new TypeName(keyword, concatAnnotations(annotations));
}
public TypeName withoutAnnotations() {
return new TypeName(keyword);
}
protected final List<AnnotationSpec> concatAnnotations(List<AnnotationSpec> annotations) {
List<AnnotationSpec> allAnnotations = new ArrayList<>(this.annotations);
allAnnotations.addAll(annotations);
return allAnnotations;
}
public boolean isAnnotated() {
return !annotations.isEmpty();
}
/**
* Returns true if this is a primitive type like {@code int}. Returns false for all other types
* types including boxed primitives and {@code void}.
*/
public boolean isPrimitive() {
return keyword != null && this != VOID;
}
/**
* Returns true if this is a boxed primitive type like {@code Integer}. Returns false for all
* other types types including unboxed primitives and {@code java.lang.Void}.
*/
public boolean isBoxedPrimitive() {
return this.equals(BOXED_BOOLEAN)
|| this.equals(BOXED_BYTE)
|| this.equals(BOXED_SHORT)
|| this.equals(BOXED_INT)
|| this.equals(BOXED_LONG)
|| this.equals(BOXED_CHAR)
|| this.equals(BOXED_FLOAT)
|| this.equals(BOXED_DOUBLE);
}
/**
* Returns a boxed type if this is a primitive type (like {@code Integer} for {@code int}) or
* {@code void}. Returns this type if boxing doesn't apply.
*/
public TypeName box() {
if (keyword == null) return this; // Doesn't need boxing.
if (this == VOID) return BOXED_VOID;
if (this == BOOLEAN) return BOXED_BOOLEAN;
if (this == BYTE) return BOXED_BYTE;
if (this == SHORT) return BOXED_SHORT;
if (this == INT) return BOXED_INT;
if (this == LONG) return BOXED_LONG;
if (this == CHAR) return BOXED_CHAR;
if (this == FLOAT) return BOXED_FLOAT;
if (this == DOUBLE) return BOXED_DOUBLE;
throw new AssertionError(keyword);
}
/**
* Returns an unboxed type if this is a boxed primitive type (like {@code int} for {@code
* Integer}) or {@code Void}. Returns this type if it is already unboxed.
*
* @throws UnsupportedOperationException if this type isn't eligible for unboxing.
*/
public TypeName unbox() {
if (keyword != null) return this; // Already unboxed.
if (this.equals(BOXED_VOID)) return VOID;
if (this.equals(BOXED_BOOLEAN)) return BOOLEAN;
if (this.equals(BOXED_BYTE)) return BYTE;
if (this.equals(BOXED_SHORT)) return SHORT;
if (this.equals(BOXED_INT)) return INT;
if (this.equals(BOXED_LONG)) return LONG;
if (this.equals(BOXED_CHAR)) return CHAR;
if (this.equals(BOXED_FLOAT)) return FLOAT;
if (this.equals(BOXED_DOUBLE)) return DOUBLE;
throw new UnsupportedOperationException("cannot unbox " + this);
}
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
return toString().equals(o.toString());
}
@Override
public final int hashCode() {
return toString().hashCode();
}
@Override
public final String toString() {
String result = cachedString;
if (result == null) {
try {
StringBuilder resultBuilder = new StringBuilder();
CodeWriter codeWriter = new CodeWriter(resultBuilder);
emitAnnotations(codeWriter);
emit(codeWriter);
result = resultBuilder.toString();
cachedString = result;
} catch (IOException e) {
throw new AssertionError();
}
}
return result;
}
CodeWriter emit(CodeWriter out) throws IOException {
if (keyword == null) throw new AssertionError();
return out.emitAndIndent(keyword);
}
CodeWriter emitAnnotations(CodeWriter out) throws IOException {
for (AnnotationSpec annotation : annotations) {
annotation.emit(out, true);
out.emit(" ");
}
return out;
}
/** Returns a type name equivalent to {@code mirror}. */
public static TypeName get(TypeMirror mirror) {
return get(mirror, new LinkedHashMap<TypeParameterElement, TypeVariableName>());
}
static TypeName get(
TypeMirror mirror, final Map<TypeParameterElement, TypeVariableName> typeVariables) {
return mirror.accept(
new SimpleTypeVisitor7<TypeName, Void>() {
@Override
public TypeName visitPrimitive(PrimitiveType t, Void p) {
switch (t.getKind()) {
case BOOLEAN:
return TypeName.BOOLEAN;
case BYTE:
return TypeName.BYTE;
case SHORT:
return TypeName.SHORT;
case INT:
return TypeName.INT;
case LONG:
return TypeName.LONG;
case CHAR:
return TypeName.CHAR;
case FLOAT:
return TypeName.FLOAT;
case DOUBLE:
return TypeName.DOUBLE;
default:
throw new AssertionError();
}
}
@Override
public TypeName visitDeclared(DeclaredType t, Void p) {
ClassName rawType = ClassName.get((TypeElement) t.asElement());
TypeMirror enclosingType = t.getEnclosingType();
TypeName enclosing =
(enclosingType.getKind() != TypeKind.NONE)
&& !t.asElement().getModifiers().contains(Modifier.STATIC)
? enclosingType.accept(this, null)
: null;
if (t.getTypeArguments().isEmpty() && !(enclosing instanceof ParameterizedTypeName)) {
return rawType;
}
List<TypeName> typeArgumentNames = new ArrayList<>();
for (TypeMirror mirror : t.getTypeArguments()) {
typeArgumentNames.add(get(mirror, typeVariables));
}
return enclosing instanceof ParameterizedTypeName
? ((ParameterizedTypeName) enclosing)
.nestedClass(rawType.simpleName(), typeArgumentNames)
: new ParameterizedTypeName(null, rawType, typeArgumentNames);
}
@Override
public TypeName visitError(ErrorType t, Void p) {
return visitDeclared(t, p);
}
@Override
public ArrayTypeName visitArray(ArrayType t, Void p) {
return ArrayTypeName.get(t, typeVariables);
}
@Override
public TypeName visitTypeVariable(
org.openjdk.javax.lang.model.type.TypeVariable t, Void p) {
return TypeVariableName.get(t, typeVariables);
}
@Override
public TypeName visitWildcard(org.openjdk.javax.lang.model.type.WildcardType t, Void p) {
return WildcardTypeName.get(t, typeVariables);
}
@Override
public TypeName visitNoType(NoType t, Void p) {
if (t.getKind() == TypeKind.VOID) return TypeName.VOID;
return super.visitUnknown(t, p);
}
@Override
protected TypeName defaultAction(TypeMirror e, Void p) {
throw new IllegalArgumentException("Unexpected type mirror: " + e);
}
},
null);
}
/** Returns a type name equivalent to {@code type}. */
public static TypeName get(Type type) {
return get(type, new LinkedHashMap<Type, TypeVariableName>());
}
static TypeName get(Type type, Map<Type, TypeVariableName> map) {
if (type instanceof Class<?>) {
Class<?> classType = (Class<?>) type;
if (type == void.class) return VOID;
if (type == boolean.class) return BOOLEAN;
if (type == byte.class) return BYTE;
if (type == short.class) return SHORT;
if (type == int.class) return INT;
if (type == long.class) return LONG;
if (type == char.class) return CHAR;
if (type == float.class) return FLOAT;
if (type == double.class) return DOUBLE;
if (classType.isArray()) return ArrayTypeName.of(get(classType.getComponentType(), map));
return ClassName.get(classType);
} else if (type instanceof ParameterizedType) {
return ParameterizedTypeName.get((ParameterizedType) type, map);
} else if (type instanceof WildcardType) {
return WildcardTypeName.get((WildcardType) type, map);
} else if (type instanceof TypeVariable<?>) {
return TypeVariableName.get((TypeVariable<?>) type, map);
} else if (type instanceof GenericArrayType) {
return ArrayTypeName.get((GenericArrayType) type, map);
} else {
throw new IllegalArgumentException("unexpected type: " + type);
}
}
/** Converts an array of types to a list of type names. */
static List<TypeName> list(Type[] types) {
return list(types, new LinkedHashMap<Type, TypeVariableName>());
}
static List<TypeName> list(Type[] types, Map<Type, TypeVariableName> map) {
List<TypeName> result = new ArrayList<>(types.length);
for (Type type : types) {
result.add(get(type, map));
}
return result;
}
/** Returns the array component of {@code type}, or null if {@code type} is not an array. */
static TypeName arrayComponent(TypeName type) {
return type instanceof ArrayTypeName ? ((ArrayTypeName) type).componentType : null;
}
}
| 14,601 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AnnotationSpec.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/AnnotationSpec.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.characterLiteralWithoutSingleQuotes;
import static com.squareup.javapoet.Util.checkNotNull;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.openjdk.javax.lang.model.element.AnnotationMirror;
import org.openjdk.javax.lang.model.element.AnnotationValue;
import org.openjdk.javax.lang.model.element.ExecutableElement;
import org.openjdk.javax.lang.model.element.TypeElement;
import org.openjdk.javax.lang.model.element.VariableElement;
import org.openjdk.javax.lang.model.type.TypeMirror;
import org.openjdk.javax.lang.model.util.SimpleAnnotationValueVisitor7;
/** A generated annotation on a declaration. */
public final class AnnotationSpec {
public final TypeName type;
public final Map<String, List<CodeBlock>> members;
private AnnotationSpec(Builder builder) {
this.type = builder.type;
this.members = Util.immutableMultimap(builder.members);
}
void emit(CodeWriter codeWriter, boolean inline) throws IOException {
String whitespace = inline ? "" : "\n";
String memberSeparator = inline ? ", " : ",\n";
if (members.isEmpty()) {
// @Singleton
codeWriter.emit("@$T", type);
} else if (members.size() == 1 && members.containsKey("value")) {
// @Named("foo")
codeWriter.emit("@$T(", type);
emitAnnotationValues(codeWriter, whitespace, memberSeparator, members.get("value"));
codeWriter.emit(")");
} else {
// Inline:
// @Column(name = "updated_at", nullable = false)
//
// Not inline:
// @Column(
// name = "updated_at",
// nullable = false
// )
codeWriter.emit("@$T(" + whitespace, type);
codeWriter.indent(2);
for (Iterator<Map.Entry<String, List<CodeBlock>>> i = members.entrySet().iterator();
i.hasNext(); ) {
Map.Entry<String, List<CodeBlock>> entry = i.next();
codeWriter.emit("$L = ", entry.getKey());
emitAnnotationValues(codeWriter, whitespace, memberSeparator, entry.getValue());
if (i.hasNext()) codeWriter.emit(memberSeparator);
}
codeWriter.unindent(2);
codeWriter.emit(whitespace + ")");
}
}
private void emitAnnotationValues(
CodeWriter codeWriter, String whitespace, String memberSeparator, List<CodeBlock> values)
throws IOException {
if (values.size() == 1) {
codeWriter.indent(2);
codeWriter.emit(values.get(0));
codeWriter.unindent(2);
return;
}
codeWriter.emit("{" + whitespace);
codeWriter.indent(2);
boolean first = true;
for (CodeBlock codeBlock : values) {
if (!first) codeWriter.emit(memberSeparator);
codeWriter.emit(codeBlock);
first = false;
}
codeWriter.unindent(2);
codeWriter.emit(whitespace + "}");
}
public static AnnotationSpec get(Annotation annotation) {
return get(annotation, false);
}
public static AnnotationSpec get(Annotation annotation, boolean includeDefaultValues) {
Builder builder = builder(annotation.annotationType());
try {
Method[] methods = annotation.annotationType().getDeclaredMethods();
Arrays.sort(
methods,
new Comparator<Method>() {
@Override
public int compare(Method m1, Method m2) {
return m1.getName().compareTo(m2.getName());
}
});
for (Method method : methods) {
Object value = method.invoke(annotation);
if (!includeDefaultValues) {
if (Objects.deepEquals(value, method.getDefaultValue())) {
continue;
}
}
if (value.getClass().isArray()) {
for (int i = 0; i < Array.getLength(value); i++) {
builder.addMemberForValue(method.getName(), Array.get(value, i));
}
continue;
}
if (value instanceof Annotation) {
builder.addMember(method.getName(), "$L", get((Annotation) value));
continue;
}
builder.addMemberForValue(method.getName(), value);
}
} catch (Exception e) {
throw new RuntimeException("Reflecting " + annotation + " failed!", e);
}
return builder.build();
}
public static AnnotationSpec get(AnnotationMirror annotation) {
TypeElement element = (TypeElement) annotation.getAnnotationType().asElement();
AnnotationSpec.Builder builder = AnnotationSpec.builder(ClassName.get(element));
Visitor visitor = new Visitor(builder);
for (ExecutableElement executableElement : annotation.getElementValues().keySet()) {
String name = executableElement.getSimpleName().toString();
AnnotationValue value = annotation.getElementValues().get(executableElement);
value.accept(visitor, name);
}
return builder.build();
}
public static Builder builder(ClassName type) {
checkNotNull(type, "type == null");
return new Builder(type);
}
public static Builder builder(Class<?> type) {
return builder(ClassName.get(type));
}
public Builder toBuilder() {
Builder builder = new Builder(type);
for (Map.Entry<String, List<CodeBlock>> entry : members.entrySet()) {
builder.members.put(entry.getKey(), new ArrayList<>(entry.getValue()));
}
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
return toString().equals(o.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
try {
CodeWriter codeWriter = new CodeWriter(out);
codeWriter.emit("$L", this);
return out.toString();
} catch (IOException e) {
throw new AssertionError();
}
}
public static final class Builder {
private final TypeName type;
private final Map<String, List<CodeBlock>> members = new LinkedHashMap<>();
private Builder(TypeName type) {
this.type = type;
}
public Builder addMember(String name, String format, Object... args) {
return addMember(name, CodeBlock.of(format, args));
}
public Builder addMember(String name, CodeBlock codeBlock) {
List<CodeBlock> values = members.get(name);
if (values == null) {
values = new ArrayList<>();
members.put(name, values);
}
values.add(codeBlock);
return this;
}
/**
* Delegates to {@link #addMember(String, String, Object...)}, with parameter {@code format}
* depending on the given {@code value} object. Falls back to {@code "$L"} literal format if the
* class of the given {@code value} object is not supported.
*/
Builder addMemberForValue(String memberName, Object value) {
checkNotNull(memberName, "memberName == null");
checkNotNull(value, "value == null, constant non-null value expected for %s", memberName);
if (value instanceof Class<?>) {
return addMember(memberName, "$T.class", value);
}
if (value instanceof Enum) {
return addMember(memberName, "$T.$L", value.getClass(), ((Enum<?>) value).name());
}
if (value instanceof String) {
return addMember(memberName, "$S", value);
}
if (value instanceof Float) {
return addMember(memberName, "$Lf", value);
}
if (value instanceof Character) {
return addMember(memberName, "'$L'", characterLiteralWithoutSingleQuotes((char) value));
}
return addMember(memberName, "$L", value);
}
public AnnotationSpec build() {
return new AnnotationSpec(this);
}
}
/** Annotation value visitor adding members to the given builder instance. */
private static class Visitor extends SimpleAnnotationValueVisitor7<Builder, String> {
final Builder builder;
Visitor(Builder builder) {
super(builder);
this.builder = builder;
}
@Override
protected Builder defaultAction(Object o, String name) {
return builder.addMemberForValue(name, o);
}
@Override
public Builder visitAnnotation(AnnotationMirror a, String name) {
return builder.addMember(name, "$L", get(a));
}
@Override
public Builder visitEnumConstant(VariableElement c, String name) {
return builder.addMember(name, "$T.$L", c.asType(), c.getSimpleName());
}
@Override
public Builder visitType(TypeMirror t, String name) {
return builder.addMember(name, "$T.class", t);
}
@Override
public Builder visitArray(List<? extends AnnotationValue> values, String name) {
for (AnnotationValue value : values) {
value.accept(this, name);
}
return builder;
}
}
}
| 9,706 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
WildcardTypeName.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/WildcardTypeName.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import java.io.IOException;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.openjdk.javax.lang.model.element.TypeParameterElement;
import org.openjdk.javax.lang.model.type.TypeMirror;
public final class WildcardTypeName extends TypeName {
public final List<TypeName> upperBounds;
public final List<TypeName> lowerBounds;
private WildcardTypeName(List<TypeName> upperBounds, List<TypeName> lowerBounds) {
this(upperBounds, lowerBounds, new ArrayList<AnnotationSpec>());
}
private WildcardTypeName(
List<TypeName> upperBounds, List<TypeName> lowerBounds, List<AnnotationSpec> annotations) {
super(annotations);
this.upperBounds = Util.immutableList(upperBounds);
this.lowerBounds = Util.immutableList(lowerBounds);
checkArgument(this.upperBounds.size() == 1, "unexpected extends bounds: %s", upperBounds);
for (TypeName upperBound : this.upperBounds) {
checkArgument(
!upperBound.isPrimitive() && upperBound != VOID, "invalid upper bound: %s", upperBound);
}
for (TypeName lowerBound : this.lowerBounds) {
checkArgument(
!lowerBound.isPrimitive() && lowerBound != VOID, "invalid lower bound: %s", lowerBound);
}
}
@Override
public WildcardTypeName annotated(List<AnnotationSpec> annotations) {
return new WildcardTypeName(upperBounds, lowerBounds, concatAnnotations(annotations));
}
@Override
public TypeName withoutAnnotations() {
return new WildcardTypeName(upperBounds, lowerBounds);
}
@Override
CodeWriter emit(CodeWriter out) throws IOException {
if (lowerBounds.size() == 1) {
return out.emit("? super $T", lowerBounds.get(0));
}
return upperBounds.get(0).equals(TypeName.OBJECT)
? out.emit("?")
: out.emit("? extends $T", upperBounds.get(0));
}
/**
* Returns a type that represents an unknown type that extends {@code bound}. For example, if
* {@code bound} is {@code CharSequence.class}, this returns {@code ? extends CharSequence}. If
* {@code bound} is {@code Object.class}, this returns {@code ?}, which is shorthand for {@code ?
* extends Object}.
*/
public static WildcardTypeName subtypeOf(TypeName upperBound) {
return new WildcardTypeName(Arrays.asList(upperBound), Collections.<TypeName>emptyList());
}
public static WildcardTypeName subtypeOf(Type upperBound) {
return subtypeOf(TypeName.get(upperBound));
}
/**
* Returns a type that represents an unknown supertype of {@code bound}. For example, if {@code
* bound} is {@code String.class}, this returns {@code ? super String}.
*/
public static WildcardTypeName supertypeOf(TypeName lowerBound) {
return new WildcardTypeName(Arrays.<TypeName>asList(OBJECT), Arrays.asList(lowerBound));
}
public static WildcardTypeName supertypeOf(Type lowerBound) {
return supertypeOf(TypeName.get(lowerBound));
}
public static TypeName get(org.openjdk.javax.lang.model.type.WildcardType mirror) {
return get(mirror, new LinkedHashMap<TypeParameterElement, TypeVariableName>());
}
static TypeName get(
org.openjdk.javax.lang.model.type.WildcardType mirror,
Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeMirror extendsBound = mirror.getExtendsBound();
if (extendsBound == null) {
TypeMirror superBound = mirror.getSuperBound();
if (superBound == null) {
return subtypeOf(Object.class);
} else {
return supertypeOf(TypeName.get(superBound, typeVariables));
}
} else {
return subtypeOf(TypeName.get(extendsBound, typeVariables));
}
}
public static TypeName get(WildcardType wildcardName) {
return get(wildcardName, new LinkedHashMap<Type, TypeVariableName>());
}
static TypeName get(WildcardType wildcardName, Map<Type, TypeVariableName> map) {
return new WildcardTypeName(
list(wildcardName.getUpperBounds(), map), list(wildcardName.getLowerBounds(), map));
}
}
| 4,838 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ParameterizedTypeName.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/ParameterizedTypeName.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class ParameterizedTypeName extends TypeName {
private final ParameterizedTypeName enclosingType;
public final ClassName rawType;
public final List<TypeName> typeArguments;
ParameterizedTypeName(
ParameterizedTypeName enclosingType, ClassName rawType, List<TypeName> typeArguments) {
this(enclosingType, rawType, typeArguments, new ArrayList<AnnotationSpec>());
}
private ParameterizedTypeName(
ParameterizedTypeName enclosingType,
ClassName rawType,
List<TypeName> typeArguments,
List<AnnotationSpec> annotations) {
super(annotations);
this.rawType = checkNotNull(rawType, "rawType == null");
this.enclosingType = enclosingType;
this.typeArguments = Util.immutableList(typeArguments);
checkArgument(
!this.typeArguments.isEmpty() || enclosingType != null, "no type arguments: %s", rawType);
for (TypeName typeArgument : this.typeArguments) {
checkArgument(
!typeArgument.isPrimitive() && typeArgument != VOID,
"invalid type parameter: %s",
typeArgument);
}
}
@Override
public ParameterizedTypeName annotated(List<AnnotationSpec> annotations) {
return new ParameterizedTypeName(
enclosingType, rawType, typeArguments, concatAnnotations(annotations));
}
@Override
public TypeName withoutAnnotations() {
return new ParameterizedTypeName(
enclosingType, rawType, typeArguments, new ArrayList<AnnotationSpec>());
}
@Override
CodeWriter emit(CodeWriter out) throws IOException {
if (enclosingType != null) {
enclosingType.emitAnnotations(out);
enclosingType.emit(out);
out.emit("." + rawType.simpleName());
} else {
rawType.emitAnnotations(out);
rawType.emit(out);
}
if (!typeArguments.isEmpty()) {
out.emitAndIndent("<");
boolean firstParameter = true;
for (TypeName parameter : typeArguments) {
if (!firstParameter) out.emitAndIndent(", ");
parameter.emitAnnotations(out);
parameter.emit(out);
firstParameter = false;
}
out.emitAndIndent(">");
}
return out;
}
/**
* Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
* inside this class.
*/
public ParameterizedTypeName nestedClass(String name) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(
this,
rawType.nestedClass(name),
new ArrayList<TypeName>(),
new ArrayList<AnnotationSpec>());
}
/**
* Returns a new {@link ParameterizedTypeName} instance for the specified {@code name} as nested
* inside this class, with the specified {@code typeArguments}.
*/
public ParameterizedTypeName nestedClass(String name, List<TypeName> typeArguments) {
checkNotNull(name, "name == null");
return new ParameterizedTypeName(
this, rawType.nestedClass(name), typeArguments, new ArrayList<AnnotationSpec>());
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}. */
public static ParameterizedTypeName get(ClassName rawType, TypeName... typeArguments) {
return new ParameterizedTypeName(null, rawType, Arrays.asList(typeArguments));
}
/** Returns a parameterized type, applying {@code typeArguments} to {@code rawType}. */
public static ParameterizedTypeName get(Class<?> rawType, Type... typeArguments) {
return new ParameterizedTypeName(null, ClassName.get(rawType), list(typeArguments));
}
/** Returns a parameterized type equivalent to {@code type}. */
public static ParameterizedTypeName get(ParameterizedType type) {
return get(type, new LinkedHashMap<Type, TypeVariableName>());
}
/** Returns a parameterized type equivalent to {@code type}. */
static ParameterizedTypeName get(ParameterizedType type, Map<Type, TypeVariableName> map) {
ClassName rawType = ClassName.get((Class<?>) type.getRawType());
ParameterizedType ownerType =
(type.getOwnerType() instanceof ParameterizedType)
&& !Modifier.isStatic(((Class<?>) type.getRawType()).getModifiers())
? (ParameterizedType) type.getOwnerType()
: null;
List<TypeName> typeArguments = TypeName.list(type.getActualTypeArguments(), map);
return (ownerType != null)
? get(ownerType, map).nestedClass(rawType.simpleName(), typeArguments)
: new ParameterizedTypeName(null, rawType, typeArguments);
}
}
| 5,497 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ArrayTypeName.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/ArrayTypeName.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkNotNull;
import java.io.IOException;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.openjdk.javax.lang.model.element.TypeParameterElement;
import org.openjdk.javax.lang.model.type.ArrayType;
public final class ArrayTypeName extends TypeName {
public final TypeName componentType;
private ArrayTypeName(TypeName componentType) {
this(componentType, new ArrayList<AnnotationSpec>());
}
private ArrayTypeName(TypeName componentType, List<AnnotationSpec> annotations) {
super(annotations);
this.componentType = checkNotNull(componentType, "rawType == null");
}
@Override
public ArrayTypeName annotated(List<AnnotationSpec> annotations) {
return new ArrayTypeName(componentType, concatAnnotations(annotations));
}
@Override
public TypeName withoutAnnotations() {
return new ArrayTypeName(componentType);
}
@Override
CodeWriter emit(CodeWriter out) throws IOException {
return out.emit("$T[]", componentType);
}
/** Returns an array type whose elements are all instances of {@code componentType}. */
public static ArrayTypeName of(TypeName componentType) {
return new ArrayTypeName(componentType);
}
/** Returns an array type whose elements are all instances of {@code componentType}. */
public static ArrayTypeName of(Type componentType) {
return of(TypeName.get(componentType));
}
/** Returns an array type equivalent to {@code mirror}. */
public static ArrayTypeName get(ArrayType mirror) {
return get(mirror, new LinkedHashMap<TypeParameterElement, TypeVariableName>());
}
static ArrayTypeName get(
ArrayType mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
return new ArrayTypeName(get(mirror.getComponentType(), typeVariables));
}
/** Returns an array type equivalent to {@code type}. */
public static ArrayTypeName get(GenericArrayType type) {
return get(type, new LinkedHashMap<Type, TypeVariableName>());
}
static ArrayTypeName get(GenericArrayType type, Map<Type, TypeVariableName> map) {
return ArrayTypeName.of(get(type.getGenericComponentType(), map));
}
}
| 2,928 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
LineWrapper.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/LineWrapper.java | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkNotNull;
import java.io.IOException;
/**
* Implements soft line wrapping on an appendable. To use, append characters using {@link #append}
* or soft-wrapping spaces using {@link #wrappingSpace}.
*/
final class LineWrapper {
private final Appendable out;
private final String indent;
private final int columnLimit;
private boolean closed;
/** Characters written since the last wrapping space that haven't yet been flushed. */
private final StringBuilder buffer = new StringBuilder();
/** The number of characters since the most recent newline. Includes both out and the buffer. */
private int column = 0;
/**
* -1 if we have no buffering; otherwise the number of {@code indent}s to write after wrapping.
*/
private int indentLevel = -1;
/**
* Null if we have no buffering; otherwise the type to pass to the next call to {@link #flush}.
*/
private FlushType nextFlush;
LineWrapper(Appendable out, String indent, int columnLimit) {
checkNotNull(out, "out == null");
this.out = out;
this.indent = indent;
this.columnLimit = columnLimit;
}
/** Emit {@code s}. This may be buffered to permit line wraps to be inserted. */
void append(String s) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (nextFlush != null) {
int nextNewline = s.indexOf('\n');
// If s doesn't cause the current line to cross the limit, buffer it and return. We'll decide
// whether or not we have to wrap it later.
if (nextNewline == -1 && column + s.length() <= columnLimit) {
buffer.append(s);
column += s.length();
return;
}
// Wrap if appending s would overflow the current line.
boolean wrap = nextNewline == -1 || column + nextNewline > columnLimit;
flush(wrap ? FlushType.WRAP : nextFlush);
}
out.append(s);
int lastNewline = s.lastIndexOf('\n');
column = lastNewline != -1 ? s.length() - lastNewline - 1 : column + s.length();
}
/** Emit either a space or a newline character. */
void wrappingSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (this.nextFlush != null) flush(nextFlush);
column++; // Increment the column even though the space is deferred to next call to flush().
this.nextFlush = FlushType.SPACE;
this.indentLevel = indentLevel;
}
/** Emit a newline character if the line will exceed it's limit, otherwise do nothing. */
void zeroWidthSpace(int indentLevel) throws IOException {
if (closed) throw new IllegalStateException("closed");
if (this.nextFlush != null) flush(nextFlush);
this.nextFlush = FlushType.EMPTY;
this.indentLevel = indentLevel;
}
/** Flush any outstanding text and forbid future writes to this line wrapper. */
void close() throws IOException {
if (nextFlush != null) flush(nextFlush);
closed = true;
}
/** Write the space followed by any buffered text that follows it. */
private void flush(FlushType flushType) throws IOException {
switch (flushType) {
case WRAP:
out.append('\n');
for (int i = 0; i < indentLevel; i++) {
out.append(indent);
}
column = indentLevel * indent.length();
column += buffer.length();
break;
case SPACE:
out.append(' ');
break;
case EMPTY:
break;
default:
throw new IllegalArgumentException("Unknown FlushType: " + flushType);
}
out.append(buffer);
buffer.delete(0, buffer.length());
indentLevel = -1;
nextFlush = null;
}
private enum FlushType {
WRAP,
SPACE,
EMPTY;
}
}
| 4,367 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ParameterSpec.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/ParameterSpec.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.openjdk.javax.lang.model.SourceVersion;
import org.openjdk.javax.lang.model.element.ExecutableElement;
import org.openjdk.javax.lang.model.element.Modifier;
import org.openjdk.javax.lang.model.element.VariableElement;
/** A generated parameter declaration. */
public final class ParameterSpec {
public final String name;
public final List<AnnotationSpec> annotations;
public final Set<Modifier> modifiers;
public final TypeName type;
private ParameterSpec(Builder builder) {
this.name = checkNotNull(builder.name, "name == null");
this.annotations = Util.immutableList(builder.annotations);
this.modifiers = Util.immutableSet(builder.modifiers);
this.type = checkNotNull(builder.type, "type == null");
}
public boolean hasModifier(Modifier modifier) {
return modifiers.contains(modifier);
}
void emit(CodeWriter codeWriter, boolean varargs) throws IOException {
codeWriter.emitAnnotations(annotations, true);
codeWriter.emitModifiers(modifiers);
if (varargs) {
codeWriter.emit("$T... $L", TypeName.arrayComponent(type), name);
} else {
codeWriter.emit("$T $L", type, name);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
return toString().equals(o.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
try {
CodeWriter codeWriter = new CodeWriter(out);
emit(codeWriter, false);
return out.toString();
} catch (IOException e) {
throw new AssertionError();
}
}
public static ParameterSpec get(VariableElement element) {
TypeName type = TypeName.get(element.asType());
String name = element.getSimpleName().toString();
return ParameterSpec.builder(type, name).addModifiers(element.getModifiers()).build();
}
static List<ParameterSpec> parametersOf(ExecutableElement method) {
List<ParameterSpec> result = new ArrayList<>();
for (VariableElement parameter : method.getParameters()) {
result.add(ParameterSpec.get(parameter));
}
return result;
}
public static Builder builder(TypeName type, String name, Modifier... modifiers) {
checkNotNull(type, "type == null");
checkArgument(SourceVersion.isName(name), "not a valid name: %s", name);
return new Builder(type, name).addModifiers(modifiers);
}
public static Builder builder(Type type, String name, Modifier... modifiers) {
return builder(TypeName.get(type), name, modifiers);
}
public Builder toBuilder() {
return toBuilder(type, name);
}
Builder toBuilder(TypeName type, String name) {
Builder builder = new Builder(type, name);
builder.annotations.addAll(annotations);
builder.modifiers.addAll(modifiers);
return builder;
}
public static final class Builder {
private final TypeName type;
private final String name;
private final List<AnnotationSpec> annotations = new ArrayList<>();
private final List<Modifier> modifiers = new ArrayList<>();
private Builder(TypeName type, String name) {
this.type = type;
this.name = name;
}
public Builder addAnnotations(Iterable<AnnotationSpec> annotationSpecs) {
checkArgument(annotationSpecs != null, "annotationSpecs == null");
for (AnnotationSpec annotationSpec : annotationSpecs) {
this.annotations.add(annotationSpec);
}
return this;
}
public Builder addAnnotation(AnnotationSpec annotationSpec) {
this.annotations.add(annotationSpec);
return this;
}
public Builder addAnnotation(ClassName annotation) {
this.annotations.add(AnnotationSpec.builder(annotation).build());
return this;
}
public Builder addAnnotation(Class<?> annotation) {
return addAnnotation(ClassName.get(annotation));
}
public Builder addModifiers(Modifier... modifiers) {
Collections.addAll(this.modifiers, modifiers);
return this;
}
public Builder addModifiers(Iterable<Modifier> modifiers) {
checkNotNull(modifiers, "modifiers == null");
for (Modifier modifier : modifiers) {
this.modifiers.add(modifier);
}
return this;
}
public ParameterSpec build() {
return new ParameterSpec(this);
}
}
}
| 5,353 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CodeBlock.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/CodeBlock.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collector;
import java.util.stream.StreamSupport;
import org.openjdk.javax.lang.model.element.Element;
import org.openjdk.javax.lang.model.type.TypeMirror;
/**
* A fragment of a .java file, potentially containing declarations, statements, and documentation.
* Code blocks are not necessarily well-formed Java code, and are not validated. This class assumes
* javac will check correctness later!
*
* <p>Code blocks support placeholders like {@link java.text.Format}. Where {@link String#format}
* uses percent {@code %} to reference target values, this class uses dollar sign {@code $} and has
* its own set of permitted placeholders:
*
* <ul>
* <li>{@code $L} emits a <em>literal</em> value with no escaping. Arguments for literals may be
* strings, primitives, {@linkplain TypeSpec type declarations}, {@linkplain AnnotationSpec
* annotations} and even other code blocks.
* <li>{@code $N} emits a <em>name</em>, using name collision avoidance where necessary. Arguments
* for names may be strings (actually any {@linkplain CharSequence character sequence}),
* {@linkplain ParameterSpec parameters}, {@linkplain FieldSpec fields}, {@linkplain
* MethodSpec methods}, and {@linkplain TypeSpec types}.
* <li>{@code $S} escapes the value as a <em>string</em>, wraps it with double quotes, and emits
* that. For example, {@code 6" sandwich} is emitted {@code "6\" sandwich"}.
* <li>{@code $T} emits a <em>type</em> reference. Types will be imported if possible. Arguments
* for types may be {@linkplain Class classes}, {@linkplain
* org.openjdk.javax.lang.model.type.TypeMirror ,* type mirrors}, and {@linkplain
* org.openjdk.javax.lang.model.element.Element elements}.
* <li>{@code $$} emits a dollar sign.
* <li>{@code $W} emits a space or a newline, depending on its position on the line. This prefers
* to wrap lines before 100 columns.
* <li>{@code $Z} acts as a zero-width space. This prefers to wrap lines before 100 columns.
* <li>{@code $>} increases the indentation level.
* <li>{@code $<} decreases the indentation level.
* <li>{@code $[} begins a statement. For multiline statements, every line after the first line is
* double-indented.
* <li>{@code $]} ends a statement.
* </ul>
*/
public final class CodeBlock {
private static final Pattern NAMED_ARGUMENT =
Pattern.compile("\\$(?<argumentName>[\\w_]+):(?<typeChar>[\\w]).*");
private static final Pattern LOWERCASE = Pattern.compile("[a-z]+[\\w_]*");
/** A heterogeneous list containing string literals and value placeholders. */
final List<String> formatParts;
final List<Object> args;
private CodeBlock(Builder builder) {
this.formatParts = Util.immutableList(builder.formatParts);
this.args = Util.immutableList(builder.args);
}
public boolean isEmpty() {
return formatParts.isEmpty();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
return toString().equals(o.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
try {
new CodeWriter(out).emit(this);
return out.toString();
} catch (IOException e) {
throw new AssertionError();
}
}
public static CodeBlock of(String format, Object... args) {
return new Builder().add(format, args).build();
}
/**
* Joins {@code codeBlocks} into a single {@link CodeBlock}, each separated by {@code separator}.
* For example, joining {@code String s}, {@code Object o} and {@code int i} using {@code ", "}
* would produce {@code String s, Object o, int i}.
*/
public static CodeBlock join(Iterable<CodeBlock> codeBlocks, String separator) {
return StreamSupport.stream(codeBlocks.spliterator(), false).collect(joining(separator));
}
/**
* A {@link Collector} implementation that joins {@link CodeBlock} instances together into one
* separated by {@code separator}. For example, joining {@code String s}, {@code Object o} and
* {@code int i} using {@code ", "} would produce {@code String s, Object o, int i}.
*/
public static Collector<CodeBlock, ?, CodeBlock> joining(String separator) {
return Collector.of(
() -> new CodeBlockJoiner(separator, builder()),
CodeBlockJoiner::add,
CodeBlockJoiner::merge,
CodeBlockJoiner::join);
}
/**
* A {@link Collector} implementation that joins {@link CodeBlock} instances together into one
* separated by {@code separator}. For example, joining {@code String s}, {@code Object o} and
* {@code int i} using {@code ", "} would produce {@code String s, Object o, int i}.
*/
public static Collector<CodeBlock, ?, CodeBlock> joining(
String separator, String prefix, String suffix) {
Builder builder = builder().add("$N", prefix);
return Collector.of(
() -> new CodeBlockJoiner(separator, builder),
CodeBlockJoiner::add,
CodeBlockJoiner::merge,
joiner -> {
builder.add(CodeBlock.of("$N", suffix));
return joiner.join();
});
}
public static Builder builder() {
return new Builder();
}
public Builder toBuilder() {
Builder builder = new Builder();
builder.formatParts.addAll(formatParts);
builder.args.addAll(args);
return builder;
}
public static final class Builder {
final List<String> formatParts = new ArrayList<>();
final List<Object> args = new ArrayList<>();
private Builder() {}
public boolean isEmpty() {
return formatParts.isEmpty();
}
/**
* Adds code using named arguments.
*
* <p>Named arguments specify their name after the '$' followed by : and the corresponding type
* character. Argument names consist of characters in {@code a-z, A-Z, 0-9, and _} and must
* start with a lowercase character.
*
* <p>For example, to refer to the type {@link java.lang.Integer} with the argument name {@code
* clazz} use a format string containing {@code $clazz:T} and include the key {@code clazz} with
* value {@code java.lang.Integer.class} in the argument map.
*/
public Builder addNamed(String format, Map<String, ?> arguments) {
int p = 0;
for (String argument : arguments.keySet()) {
checkArgument(
LOWERCASE.matcher(argument).matches(),
"argument '%s' must start with a lowercase character",
argument);
}
while (p < format.length()) {
int nextP = format.indexOf("$", p);
if (nextP == -1) {
formatParts.add(format.substring(p, format.length()));
break;
}
if (p != nextP) {
formatParts.add(format.substring(p, nextP));
p = nextP;
}
Matcher matcher = null;
int colon = format.indexOf(':', p);
if (colon != -1) {
int endIndex = Math.min(colon + 2, format.length());
matcher = NAMED_ARGUMENT.matcher(format.substring(p, endIndex));
}
if (matcher != null && matcher.lookingAt()) {
String argumentName = matcher.group("argumentName");
checkArgument(
arguments.containsKey(argumentName), "Missing named argument for $%s", argumentName);
char formatChar = matcher.group("typeChar").charAt(0);
addArgument(format, formatChar, arguments.get(argumentName));
formatParts.add("$" + formatChar);
p += matcher.regionEnd();
} else {
checkArgument(p < format.length() - 1, "dangling $ at end");
checkArgument(
isNoArgPlaceholder(format.charAt(p + 1)),
"unknown format $%s at %s in '%s'",
format.charAt(p + 1),
p + 1,
format);
formatParts.add(format.substring(p, p + 2));
p += 2;
}
}
return this;
}
/**
* Add code with positional or relative arguments.
*
* <p>Relative arguments map 1:1 with the placeholders in the format string.
*
* <p>Positional arguments use an index after the placeholder to identify which argument index
* to use. For example, for a literal to reference the 3rd argument: "$3L" (1 based index)
*
* <p>Mixing relative and positional arguments in a call to add is invalid and will result in an
* error.
*/
public Builder add(String format, Object... args) {
boolean hasRelative = false;
boolean hasIndexed = false;
int relativeParameterCount = 0;
int[] indexedParameterCount = new int[args.length];
for (int p = 0; p < format.length(); ) {
if (format.charAt(p) != '$') {
int nextP = format.indexOf('$', p + 1);
if (nextP == -1) nextP = format.length();
formatParts.add(format.substring(p, nextP));
p = nextP;
continue;
}
p++; // '$'.
// Consume zero or more digits, leaving 'c' as the first non-digit char after the '$'.
int indexStart = p;
char c;
do {
checkArgument(p < format.length(), "dangling format characters in '%s'", format);
c = format.charAt(p++);
} while (c >= '0' && c <= '9');
int indexEnd = p - 1;
// If 'c' doesn't take an argument, we're done.
if (isNoArgPlaceholder(c)) {
checkArgument(
indexStart == indexEnd, "$$, $>, $<, $[, $], $W, and $Z may not have an index");
formatParts.add("$" + c);
continue;
}
// Find either the indexed argument, or the relative argument. (0-based).
int index;
if (indexStart < indexEnd) {
index = Integer.parseInt(format.substring(indexStart, indexEnd)) - 1;
hasIndexed = true;
if (args.length > 0) {
indexedParameterCount[index % args.length]++; // modulo is needed, checked below anyway
}
} else {
index = relativeParameterCount;
hasRelative = true;
relativeParameterCount++;
}
checkArgument(
index >= 0 && index < args.length,
"index %d for '%s' not in range (received %s arguments)",
index + 1,
format.substring(indexStart - 1, indexEnd + 1),
args.length);
checkArgument(!hasIndexed || !hasRelative, "cannot mix indexed and positional parameters");
addArgument(format, c, args[index]);
formatParts.add("$" + c);
}
if (hasRelative) {
checkArgument(
relativeParameterCount >= args.length,
"unused arguments: expected %s, received %s",
relativeParameterCount,
args.length);
}
if (hasIndexed) {
List<String> unused = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
if (indexedParameterCount[i] == 0) {
unused.add("$" + (i + 1));
}
}
String s = unused.size() == 1 ? "" : "s";
checkArgument(unused.isEmpty(), "unused argument%s: %s", s, Util.join(", ", unused));
}
return this;
}
private boolean isNoArgPlaceholder(char c) {
return c == '$' || c == '>' || c == '<' || c == '[' || c == ']' || c == 'W' || c == 'Z';
}
private void addArgument(String format, char c, Object arg) {
switch (c) {
case 'N':
this.args.add(argToName(arg));
break;
case 'L':
this.args.add(argToLiteral(arg));
break;
case 'S':
this.args.add(argToString(arg));
break;
case 'T':
this.args.add(argToType(arg));
break;
default:
throw new IllegalArgumentException(String.format("invalid format string: '%s'", format));
}
}
private String argToName(Object o) {
if (o instanceof CharSequence) return o.toString();
if (o instanceof ParameterSpec) return ((ParameterSpec) o).name;
if (o instanceof FieldSpec) return ((FieldSpec) o).name;
if (o instanceof MethodSpec) return ((MethodSpec) o).name;
if (o instanceof TypeSpec) return ((TypeSpec) o).name;
throw new IllegalArgumentException("expected name but was " + o);
}
private Object argToLiteral(Object o) {
return o;
}
private String argToString(Object o) {
return o != null ? String.valueOf(o) : null;
}
private TypeName argToType(Object o) {
if (o instanceof TypeName) return (TypeName) o;
if (o instanceof TypeMirror) return TypeName.get((TypeMirror) o);
if (o instanceof Element) return TypeName.get(((Element) o).asType());
if (o instanceof Type) return TypeName.get((Type) o);
throw new IllegalArgumentException("expected type but was " + o);
}
/**
* @param controlFlow the control flow construct and its code, such as "if (foo == 5)".
* Shouldn't contain braces or newline characters.
*/
public Builder beginControlFlow(String controlFlow, Object... args) {
add(controlFlow + " {\n", args);
indent();
return this;
}
/**
* @param controlFlow the control flow construct and its code, such as "else if (foo == 10)".
* Shouldn't contain braces or newline characters.
*/
public Builder nextControlFlow(String controlFlow, Object... args) {
unindent();
add("} " + controlFlow + " {\n", args);
indent();
return this;
}
public Builder endControlFlow() {
unindent();
add("}\n");
return this;
}
/**
* @param controlFlow the optional control flow construct and its code, such as "while(foo ==
* 20)". Only used for "do/while" control flows.
*/
public Builder endControlFlow(String controlFlow, Object... args) {
unindent();
add("} " + controlFlow + ";\n", args);
return this;
}
public Builder addStatement(String format, Object... args) {
add("$[");
add(format, args);
add(";\n$]");
return this;
}
public Builder addStatement(CodeBlock codeBlock) {
return addStatement("$L", codeBlock);
}
public Builder add(CodeBlock codeBlock) {
formatParts.addAll(codeBlock.formatParts);
args.addAll(codeBlock.args);
return this;
}
public Builder indent() {
this.formatParts.add("$>");
return this;
}
public Builder unindent() {
this.formatParts.add("$<");
return this;
}
public CodeBlock build() {
return new CodeBlock(this);
}
}
private static final class CodeBlockJoiner {
private final String delimiter;
private final Builder builder;
private boolean first = true;
CodeBlockJoiner(String delimiter, Builder builder) {
this.delimiter = delimiter;
this.builder = builder;
}
CodeBlockJoiner add(CodeBlock codeBlock) {
if (!first) {
builder.add(delimiter);
}
first = false;
builder.add(codeBlock);
return this;
}
CodeBlockJoiner merge(CodeBlockJoiner other) {
CodeBlock otherBlock = other.builder.build();
if (!otherBlock.isEmpty()) {
add(otherBlock);
}
return this;
}
CodeBlock join() {
return builder.build();
}
}
}
| 16,422 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
TypeVariableName.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/TypeVariableName.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.openjdk.javax.lang.model.element.TypeParameterElement;
import org.openjdk.javax.lang.model.type.TypeMirror;
import org.openjdk.javax.lang.model.type.TypeVariable;
public final class TypeVariableName extends TypeName {
public final String name;
public final List<TypeName> bounds;
private TypeVariableName(String name, List<TypeName> bounds) {
this(name, bounds, new ArrayList<AnnotationSpec>());
}
private TypeVariableName(String name, List<TypeName> bounds, List<AnnotationSpec> annotations) {
super(annotations);
this.name = checkNotNull(name, "name == null");
this.bounds = bounds;
for (TypeName bound : this.bounds) {
checkArgument(!bound.isPrimitive() && bound != VOID, "invalid bound: %s", bound);
}
}
@Override
public TypeVariableName annotated(List<AnnotationSpec> annotations) {
return new TypeVariableName(name, bounds, annotations);
}
@Override
public TypeName withoutAnnotations() {
return new TypeVariableName(name, bounds);
}
public TypeVariableName withBounds(Type... bounds) {
return withBounds(TypeName.list(bounds));
}
public TypeVariableName withBounds(TypeName... bounds) {
return withBounds(Arrays.asList(bounds));
}
public TypeVariableName withBounds(List<? extends TypeName> bounds) {
ArrayList<TypeName> newBounds = new ArrayList<>();
newBounds.addAll(this.bounds);
newBounds.addAll(bounds);
return new TypeVariableName(name, newBounds, annotations);
}
private static TypeVariableName of(String name, List<TypeName> bounds) {
// Strip java.lang.Object from bounds if it is present.
List<TypeName> boundsNoObject = new ArrayList<>(bounds);
boundsNoObject.remove(OBJECT);
return new TypeVariableName(name, Collections.unmodifiableList(boundsNoObject));
}
@Override
CodeWriter emit(CodeWriter out) throws IOException {
return out.emitAndIndent(name);
}
/** Returns type variable named {@code name} without bounds. */
public static TypeVariableName get(String name) {
return TypeVariableName.of(name, Collections.<TypeName>emptyList());
}
/** Returns type variable named {@code name} with {@code bounds}. */
public static TypeVariableName get(String name, TypeName... bounds) {
return TypeVariableName.of(name, Arrays.asList(bounds));
}
/** Returns type variable named {@code name} with {@code bounds}. */
public static TypeVariableName get(String name, Type... bounds) {
return TypeVariableName.of(name, TypeName.list(bounds));
}
/** Returns type variable equivalent to {@code mirror}. */
public static TypeVariableName get(TypeVariable mirror) {
return get((TypeParameterElement) mirror.asElement());
}
/**
* Make a TypeVariableName for the given TypeMirror. This form is used internally to avoid
* infinite recursion in cases like {@code Enum<E extends Enum<E>>}. When we encounter such a
* thing, we will make a TypeVariableName without bounds and add that to the {@code typeVariables}
* map before looking up the bounds. Then if we encounter this TypeVariable again while
* constructing the bounds, we can just return it from the map. And, the code that put the entry
* in {@code variables} will make sure that the bounds are filled in before returning.
*/
static TypeVariableName get(
TypeVariable mirror, Map<TypeParameterElement, TypeVariableName> typeVariables) {
TypeParameterElement element = (TypeParameterElement) mirror.asElement();
TypeVariableName typeVariableName = typeVariables.get(element);
if (typeVariableName == null) {
// Since the bounds field is public, we need to make it an unmodifiableList. But we control
// the List that that wraps, which means we can change it before returning.
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
typeVariableName = new TypeVariableName(element.getSimpleName().toString(), visibleBounds);
typeVariables.put(element, typeVariableName);
for (TypeMirror typeMirror : element.getBounds()) {
bounds.add(TypeName.get(typeMirror, typeVariables));
}
bounds.remove(OBJECT);
}
return typeVariableName;
}
/** Returns type variable equivalent to {@code element}. */
public static TypeVariableName get(TypeParameterElement element) {
String name = element.getSimpleName().toString();
List<? extends TypeMirror> boundsMirrors = element.getBounds();
List<TypeName> boundsTypeNames = new ArrayList<>();
for (TypeMirror typeMirror : boundsMirrors) {
boundsTypeNames.add(TypeName.get(typeMirror));
}
return TypeVariableName.of(name, boundsTypeNames);
}
/** Returns type variable equivalent to {@code type}. */
public static TypeVariableName get(java.lang.reflect.TypeVariable<?> type) {
return get(type, new LinkedHashMap<Type, TypeVariableName>());
}
/**
* @see #get(java.lang.reflect.TypeVariable, Map)
*/
static TypeVariableName get(
java.lang.reflect.TypeVariable<?> type, Map<Type, TypeVariableName> map) {
TypeVariableName result = map.get(type);
if (result == null) {
List<TypeName> bounds = new ArrayList<>();
List<TypeName> visibleBounds = Collections.unmodifiableList(bounds);
result = new TypeVariableName(type.getName(), visibleBounds);
map.put(type, result);
for (Type bound : type.getBounds()) {
bounds.add(TypeName.get(bound, map));
}
bounds.remove(OBJECT);
}
return result;
}
}
| 6,526 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FieldSpec.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/FieldSpec.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import static com.squareup.javapoet.Util.checkState;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.openjdk.javax.lang.model.SourceVersion;
import org.openjdk.javax.lang.model.element.Modifier;
/** A generated field declaration. */
public final class FieldSpec {
public final TypeName type;
public final String name;
public final CodeBlock javadoc;
public final List<AnnotationSpec> annotations;
public final Set<Modifier> modifiers;
public final CodeBlock initializer;
private FieldSpec(Builder builder) {
this.type = checkNotNull(builder.type, "type == null");
this.name = checkNotNull(builder.name, "name == null");
this.javadoc = builder.javadoc.build();
this.annotations = Util.immutableList(builder.annotations);
this.modifiers = Util.immutableSet(builder.modifiers);
this.initializer =
(builder.initializer == null) ? CodeBlock.builder().build() : builder.initializer;
}
public boolean hasModifier(Modifier modifier) {
return modifiers.contains(modifier);
}
void emit(CodeWriter codeWriter, Set<Modifier> implicitModifiers) throws IOException {
codeWriter.emitJavadoc(javadoc);
codeWriter.emitAnnotations(annotations, false);
codeWriter.emitModifiers(modifiers, implicitModifiers);
codeWriter.emit("$T $L", type, name);
if (!initializer.isEmpty()) {
codeWriter.emit(" = ");
codeWriter.emit(initializer);
}
codeWriter.emit(";\n");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
return toString().equals(o.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
try {
CodeWriter codeWriter = new CodeWriter(out);
emit(codeWriter, Collections.<Modifier>emptySet());
return out.toString();
} catch (IOException e) {
throw new AssertionError();
}
}
public static Builder builder(TypeName type, String name, Modifier... modifiers) {
checkNotNull(type, "type == null");
checkArgument(SourceVersion.isName(name), "not a valid name: %s", name);
return new Builder(type, name).addModifiers(modifiers);
}
public static Builder builder(Type type, String name, Modifier... modifiers) {
return builder(TypeName.get(type), name, modifiers);
}
public Builder toBuilder() {
Builder builder = new Builder(type, name);
builder.javadoc.add(javadoc);
builder.annotations.addAll(annotations);
builder.modifiers.addAll(modifiers);
builder.initializer = initializer.isEmpty() ? null : initializer;
return builder;
}
public static final class Builder {
private final TypeName type;
private final String name;
private final CodeBlock.Builder javadoc = CodeBlock.builder();
private final List<AnnotationSpec> annotations = new ArrayList<>();
private final List<Modifier> modifiers = new ArrayList<>();
private CodeBlock initializer = null;
private Builder(TypeName type, String name) {
this.type = type;
this.name = name;
}
public Builder addJavadoc(String format, Object... args) {
javadoc.add(format, args);
return this;
}
public Builder addJavadoc(CodeBlock block) {
javadoc.add(block);
return this;
}
public Builder addAnnotations(Iterable<AnnotationSpec> annotationSpecs) {
checkArgument(annotationSpecs != null, "annotationSpecs == null");
for (AnnotationSpec annotationSpec : annotationSpecs) {
this.annotations.add(annotationSpec);
}
return this;
}
public Builder addAnnotation(AnnotationSpec annotationSpec) {
this.annotations.add(annotationSpec);
return this;
}
public Builder addAnnotation(ClassName annotation) {
this.annotations.add(AnnotationSpec.builder(annotation).build());
return this;
}
public Builder addAnnotation(Class<?> annotation) {
return addAnnotation(ClassName.get(annotation));
}
public Builder addModifiers(Modifier... modifiers) {
Collections.addAll(this.modifiers, modifiers);
return this;
}
public Builder initializer(String format, Object... args) {
return initializer(CodeBlock.of(format, args));
}
public Builder initializer(CodeBlock codeBlock) {
checkState(this.initializer == null, "initializer was already set");
this.initializer = checkNotNull(codeBlock, "codeBlock == null");
return this;
}
public FieldSpec build() {
return new FieldSpec(this);
}
}
}
| 5,554 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
Util.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/Util.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static java.lang.Character.isISOControl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openjdk.javax.lang.model.element.Modifier;
/**
* Like Guava, but worse and standalone. This makes it easier to mix JavaPoet with libraries that
* bring their own version of Guava.
*/
final class Util {
private Util() {}
/** Modifier.DEFAULT doesn't exist until Java 8, but we want to run on earlier releases. */
static final Modifier DEFAULT;
static {
Modifier def = null;
try {
def = Modifier.valueOf("DEFAULT");
} catch (IllegalArgumentException ignored) {
}
DEFAULT = def;
}
static <K, V> Map<K, List<V>> immutableMultimap(Map<K, List<V>> multimap) {
LinkedHashMap<K, List<V>> result = new LinkedHashMap<>();
for (Map.Entry<K, List<V>> entry : multimap.entrySet()) {
if (entry.getValue().isEmpty()) continue;
result.put(entry.getKey(), immutableList(entry.getValue()));
}
return Collections.unmodifiableMap(result);
}
static <K, V> Map<K, V> immutableMap(Map<K, V> map) {
return Collections.unmodifiableMap(new LinkedHashMap<>(map));
}
static void checkArgument(boolean condition, String format, Object... args) {
if (!condition) throw new IllegalArgumentException(String.format(format, args));
}
static <T> T checkNotNull(T reference, String format, Object... args) {
if (reference == null) throw new NullPointerException(String.format(format, args));
return reference;
}
static void checkState(boolean condition, String format, Object... args) {
if (!condition) throw new IllegalStateException(String.format(format, args));
}
static <T> List<T> immutableList(Collection<T> collection) {
return Collections.unmodifiableList(new ArrayList<>(collection));
}
static <T> Set<T> immutableSet(Collection<T> set) {
return Collections.unmodifiableSet(new LinkedHashSet<>(set));
}
static String join(String separator, List<String> parts) {
if (parts.isEmpty()) return "";
StringBuilder result = new StringBuilder();
result.append(parts.get(0));
for (int i = 1; i < parts.size(); i++) {
result.append(separator).append(parts.get(i));
}
return result.toString();
}
static <T> Set<T> union(Set<T> a, Set<T> b) {
Set<T> result = new LinkedHashSet<>();
result.addAll(a);
result.addAll(b);
return result;
}
static void requireExactlyOneOf(Set<Modifier> modifiers, Modifier... mutuallyExclusive) {
int count = 0;
for (Modifier modifier : mutuallyExclusive) {
if (modifier == null && Util.DEFAULT == null) continue; // Skip 'DEFAULT' if it doesn't exist!
if (modifiers.contains(modifier)) count++;
}
checkArgument(
count == 1,
"modifiers %s must contain one of %s",
modifiers,
Arrays.toString(mutuallyExclusive));
}
static boolean hasDefaultModifier(Collection<Modifier> modifiers) {
return DEFAULT != null && modifiers.contains(DEFAULT);
}
static String characterLiteralWithoutSingleQuotes(char c) {
// see https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.6
switch (c) {
case '\b':
return "\\b"; /* \u0008: backspace (BS) */
case '\t':
return "\\t"; /* \u0009: horizontal tab (HT) */
case '\n':
return "\\n"; /* \u000a: linefeed (LF) */
case '\f':
return "\\f"; /* \u000c: form feed (FF) */
case '\r':
return "\\r"; /* \u000d: carriage return (CR) */
case '\"':
return "\""; /* \u0022: double quote (") */
case '\'':
return "\\'"; /* \u0027: single quote (') */
case '\\':
return "\\\\"; /* \u005c: backslash (\) */
default:
return isISOControl(c) ? String.format("\\u%04x", (int) c) : Character.toString(c);
}
}
/** Returns the string literal representing {@code value}, including wrapping double quotes. */
static String stringLiteralWithDoubleQuotes(String value, String indent) {
StringBuilder result = new StringBuilder(value.length() + 2);
result.append('"');
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
// trivial case: single quote must not be escaped
if (c == '\'') {
result.append("'");
continue;
}
// trivial case: double quotes must be escaped
if (c == '\"') {
result.append("\\\"");
continue;
}
// default case: just let character literal do its work
result.append(characterLiteralWithoutSingleQuotes(c));
// need to append indent after linefeed?
if (c == '\n' && i + 1 < value.length()) {
result.append("\"\n").append(indent).append(indent).append("+ \"");
}
}
result.append('"');
return result.toString();
}
}
| 5,639 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ClassName.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/ClassName.java | /*
* Copyright (C) 2014 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import static org.openjdk.javax.lang.model.element.NestingKind.MEMBER;
import static org.openjdk.javax.lang.model.element.NestingKind.TOP_LEVEL;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.openjdk.javax.lang.model.SourceVersion;
import org.openjdk.javax.lang.model.element.Element;
import org.openjdk.javax.lang.model.element.ElementKind;
import org.openjdk.javax.lang.model.element.PackageElement;
import org.openjdk.javax.lang.model.element.TypeElement;
/** A fully-qualified class name for top-level and member classes. */
public final class ClassName extends TypeName implements Comparable<ClassName> {
public static final ClassName OBJECT = ClassName.get(Object.class);
/** From top to bottom. This will be ["java.util", "Map", "Entry"] for {@link Map.Entry}. */
final List<String> names;
final String canonicalName;
private ClassName(List<String> names) {
this(names, new ArrayList<AnnotationSpec>());
}
private ClassName(List<String> names, List<AnnotationSpec> annotations) {
super(annotations);
for (int i = 1; i < names.size(); i++) {
checkArgument(SourceVersion.isName(names.get(i)), "part '%s' is keyword", names.get(i));
}
this.names = Util.immutableList(names);
this.canonicalName =
(names.get(0).isEmpty()
? Util.join(".", names.subList(1, names.size()))
: Util.join(".", names));
}
@Override
public ClassName annotated(List<AnnotationSpec> annotations) {
return new ClassName(names, concatAnnotations(annotations));
}
@Override
public ClassName withoutAnnotations() {
return new ClassName(names);
}
/** Returns the package name, like {@code "java.util"} for {@code Map.Entry}. */
public String packageName() {
return names.get(0);
}
/**
* Returns the enclosing class, like {@link Map} for {@code Map.Entry}. Returns null if this class
* is not nested in another class.
*/
public ClassName enclosingClassName() {
if (names.size() == 2) return null;
return new ClassName(names.subList(0, names.size() - 1));
}
/**
* Returns the top class in this nesting group. Equivalent to chained calls to {@link
* #enclosingClassName()} until the result's enclosing class is null.
*/
public ClassName topLevelClassName() {
return new ClassName(names.subList(0, 2));
}
public String reflectionName() {
// trivial case: no nested names
if (names.size() == 2) {
String packageName = packageName();
if (packageName.isEmpty()) {
return names.get(1);
}
return packageName + "." + names.get(1);
}
// concat top level class name and nested names
StringBuilder builder = new StringBuilder();
builder.append(topLevelClassName());
for (String name : simpleNames().subList(1, simpleNames().size())) {
builder.append('$').append(name);
}
return builder.toString();
}
/**
* Returns a new {@link ClassName} instance for the specified {@code name} as nested inside this
* class.
*/
public ClassName nestedClass(String name) {
checkNotNull(name, "name == null");
List<String> result = new ArrayList<>(names.size() + 1);
result.addAll(names);
result.add(name);
return new ClassName(result);
}
public List<String> simpleNames() {
return names.subList(1, names.size());
}
/**
* Returns a class that shares the same enclosing package or class. If this class is enclosed by
* another class, this is equivalent to {@code enclosingClassName().nestedClass(name)}. Otherwise
* it is equivalent to {@code get(packageName(), name)}.
*/
public ClassName peerClass(String name) {
List<String> result = new ArrayList<>(names);
result.set(result.size() - 1, name);
return new ClassName(result);
}
/** Returns the simple name of this class, like {@code "Entry"} for {@link Map.Entry}. */
public String simpleName() {
return names.get(names.size() - 1);
}
public static ClassName get(Class<?> clazz) {
checkNotNull(clazz, "clazz == null");
checkArgument(!clazz.isPrimitive(), "primitive types cannot be represented as a ClassName");
checkArgument(!void.class.equals(clazz), "'void' type cannot be represented as a ClassName");
checkArgument(!clazz.isArray(), "array types cannot be represented as a ClassName");
List<String> names = new ArrayList<>();
while (true) {
String anonymousSuffix = "";
while (clazz.isAnonymousClass()) {
int lastDollar = clazz.getName().lastIndexOf('$');
anonymousSuffix = clazz.getName().substring(lastDollar) + anonymousSuffix;
clazz = clazz.getEnclosingClass();
}
names.add(clazz.getSimpleName() + anonymousSuffix);
Class<?> enclosing = clazz.getEnclosingClass();
if (enclosing == null) break;
clazz = enclosing;
}
// Avoid unreliable Class.getPackage(). https://github.com/square/javapoet/issues/295
int lastDot = clazz.getName().lastIndexOf('.');
if (lastDot != -1) names.add(clazz.getName().substring(0, lastDot));
Collections.reverse(names);
return new ClassName(names);
}
/**
* Returns a new {@link ClassName} instance for the given fully-qualified class name string. This
* method assumes that the input is ASCII and follows typical Java style (lowercase package names,
* UpperCamelCase class names) and may produce incorrect results or throw {@link
* IllegalArgumentException} otherwise. For that reason, {@link #get(Class)} and {@link
* #get(Class)} should be preferred as they can correctly create {@link ClassName} instances
* without such restrictions.
*/
public static ClassName bestGuess(String classNameString) {
List<String> names = new ArrayList<>();
// Add the package name, like "java.util.concurrent", or "" for no package.
int p = 0;
while (p < classNameString.length() && Character.isLowerCase(classNameString.codePointAt(p))) {
p = classNameString.indexOf('.', p) + 1;
checkArgument(p != 0, "couldn't make a guess for %s", classNameString);
}
names.add(p != 0 ? classNameString.substring(0, p - 1) : "");
// Add the class names, like "Map" and "Entry".
for (String part : classNameString.substring(p).split("\\.", -1)) {
checkArgument(
!part.isEmpty() && Character.isUpperCase(part.codePointAt(0)),
"couldn't make a guess for %s",
classNameString);
names.add(part);
}
checkArgument(names.size() >= 2, "couldn't make a guess for %s", classNameString);
return new ClassName(names);
}
/**
* Returns a class name created from the given parts. For example, calling this with package name
* {@code "java.util"} and simple names {@code "Map"}, {@code "Entry"} yields {@link Map.Entry}.
*/
public static ClassName get(String packageName, String simpleName, String... simpleNames) {
List<String> result = new ArrayList<>();
result.add(packageName);
result.add(simpleName);
Collections.addAll(result, simpleNames);
return new ClassName(result);
}
/** Returns the class name for {@code element}. */
public static ClassName get(TypeElement element) {
checkNotNull(element, "element == null");
List<String> names = new ArrayList<>();
for (Element e = element; isClassOrInterface(e); e = e.getEnclosingElement()) {
checkArgument(
element.getNestingKind() == TOP_LEVEL || element.getNestingKind() == MEMBER,
"unexpected type testing");
names.add(e.getSimpleName().toString());
}
names.add(getPackage(element).getQualifiedName().toString());
Collections.reverse(names);
return new ClassName(names);
}
private static boolean isClassOrInterface(Element e) {
return e.getKind().isClass() || e.getKind().isInterface();
}
private static PackageElement getPackage(Element type) {
while (type.getKind() != ElementKind.PACKAGE) {
type = type.getEnclosingElement();
}
return (PackageElement) type;
}
@Override
public int compareTo(ClassName o) {
return canonicalName.compareTo(o.canonicalName);
}
@Override
CodeWriter emit(CodeWriter out) throws IOException {
return out.emitAndIndent(out.lookupName(this));
}
}
| 9,075 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaFile.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/JavaFile.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.openjdk.javax.annotation.processing.Filer;
import org.openjdk.javax.lang.model.element.Element;
import org.openjdk.javax.lang.model.element.Modifier;
import org.openjdk.javax.tools.JavaFileObject;
import org.openjdk.javax.tools.JavaFileObject.Kind;
import org.openjdk.javax.tools.SimpleJavaFileObject;
/** A Java file containing a single top level class. */
public final class JavaFile {
private static final Appendable NULL_APPENDABLE =
new Appendable() {
@Override
public Appendable append(CharSequence charSequence) {
return this;
}
@Override
public Appendable append(CharSequence charSequence, int start, int end) {
return this;
}
@Override
public Appendable append(char c) {
return this;
}
};
public final CodeBlock fileComment;
public final String packageName;
public final TypeSpec typeSpec;
public final boolean skipJavaLangImports;
private final Set<String> staticImports;
private final String indent;
private JavaFile(Builder builder) {
this.fileComment = builder.fileComment.build();
this.packageName = builder.packageName;
this.typeSpec = builder.typeSpec;
this.skipJavaLangImports = builder.skipJavaLangImports;
this.staticImports = Util.immutableSet(builder.staticImports);
this.indent = builder.indent;
}
public void writeTo(Appendable out) throws IOException {
// First pass: emit the entire class, just to collect the types we'll need to import.
CodeWriter importsCollector = new CodeWriter(NULL_APPENDABLE, indent, staticImports);
emit(importsCollector);
Map<String, ClassName> suggestedImports = importsCollector.suggestedImports();
// Second pass: write the code, taking advantage of the imports.
CodeWriter codeWriter = new CodeWriter(out, indent, suggestedImports, staticImports);
emit(codeWriter);
}
/** Writes this to {@code directory} as UTF-8 using the standard directory structure. */
public void writeTo(Path directory) throws IOException {
checkArgument(
Files.notExists(directory) || Files.isDirectory(directory),
"path %s exists but is not a directory.",
directory);
Path outputDirectory = directory;
if (!packageName.isEmpty()) {
for (String packageComponent : packageName.split("\\.")) {
outputDirectory = outputDirectory.resolve(packageComponent);
}
Files.createDirectories(outputDirectory);
}
Path outputPath = outputDirectory.resolve(typeSpec.name + ".java");
try (Writer writer = new OutputStreamWriter(Files.newOutputStream(outputPath), UTF_8)) {
writeTo(writer);
}
}
/** Writes this to {@code directory} as UTF-8 using the standard directory structure. */
public void writeTo(File directory) throws IOException {
writeTo(directory.toPath());
}
/** Writes this to {@code filer}. */
public void writeTo(Filer filer) throws IOException {
String fileName = packageName.isEmpty() ? typeSpec.name : packageName + "." + typeSpec.name;
List<Element> originatingElements = typeSpec.originatingElements;
JavaFileObject filerSourceFile =
filer.createSourceFile(
fileName, originatingElements.toArray(new Element[originatingElements.size()]));
try (Writer writer = filerSourceFile.openWriter()) {
writeTo(writer);
} catch (Exception e) {
try {
filerSourceFile.delete();
} catch (Exception ignored) {
}
throw e;
}
}
private void emit(CodeWriter codeWriter) throws IOException {
codeWriter.pushPackage(packageName);
if (!fileComment.isEmpty()) {
codeWriter.emitComment(fileComment);
}
if (!packageName.isEmpty()) {
codeWriter.emit("package $L;\n", packageName);
codeWriter.emit("\n");
}
if (!staticImports.isEmpty()) {
for (String signature : staticImports) {
codeWriter.emit("import static $L;\n", signature);
}
codeWriter.emit("\n");
}
int importedTypesCount = 0;
for (ClassName className : new TreeSet<>(codeWriter.importedTypes().values())) {
if (skipJavaLangImports && className.packageName().equals("java.lang")) continue;
codeWriter.emit("import $L;\n", className);
importedTypesCount++;
}
if (importedTypesCount > 0) {
codeWriter.emit("\n");
}
typeSpec.emit(codeWriter, null, Collections.<Modifier>emptySet());
codeWriter.popPackage();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
return toString().equals(o.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
try {
StringBuilder result = new StringBuilder();
writeTo(result);
return result.toString();
} catch (IOException e) {
throw new AssertionError();
}
}
public JavaFileObject toJavaFileObject() {
URI uri =
URI.create(
(packageName.isEmpty()
? typeSpec.name
: packageName.replace('.', '/') + '/' + typeSpec.name)
+ Kind.SOURCE.extension);
return new SimpleJavaFileObject(uri, Kind.SOURCE) {
private final long lastModified = System.currentTimeMillis();
@Override
public String getCharContent(boolean ignoreEncodingErrors) {
return JavaFile.this.toString();
}
@Override
public InputStream openInputStream() throws IOException {
return new ByteArrayInputStream(getCharContent(true).getBytes(UTF_8));
}
@Override
public long getLastModified() {
return lastModified;
}
};
}
public static Builder builder(String packageName, TypeSpec typeSpec) {
checkNotNull(packageName, "packageName == null");
checkNotNull(typeSpec, "typeSpec == null");
return new Builder(packageName, typeSpec);
}
public Builder toBuilder() {
Builder builder = new Builder(packageName, typeSpec);
builder.fileComment.add(fileComment);
builder.skipJavaLangImports = skipJavaLangImports;
builder.indent = indent;
return builder;
}
public static final class Builder {
private final String packageName;
private final TypeSpec typeSpec;
private final CodeBlock.Builder fileComment = CodeBlock.builder();
private final Set<String> staticImports = new TreeSet<>();
private boolean skipJavaLangImports;
private String indent = " ";
private Builder(String packageName, TypeSpec typeSpec) {
this.packageName = packageName;
this.typeSpec = typeSpec;
}
public Builder addFileComment(String format, Object... args) {
this.fileComment.add(format, args);
return this;
}
public Builder addStaticImport(Enum<?> constant) {
return addStaticImport(ClassName.get(constant.getDeclaringClass()), constant.name());
}
public Builder addStaticImport(Class<?> clazz, String... names) {
return addStaticImport(ClassName.get(clazz), names);
}
public Builder addStaticImport(ClassName className, String... names) {
checkArgument(className != null, "className == null");
checkArgument(names != null, "names == null");
checkArgument(names.length > 0, "names array is empty");
for (String name : names) {
checkArgument(name != null, "null entry in names array: %s", Arrays.toString(names));
staticImports.add(className.canonicalName + "." + name);
}
return this;
}
/**
* Call this to omit imports for classes in {@code java.lang}, such as {@code java.lang.String}.
*
* <p>By default, JavaPoet explicitly imports types in {@code java.lang} to defend against
* naming conflicts. Suppose an (ill-advised) class is named {@code com.example.String}. When
* {@code java.lang} imports are skipped, generated code in {@code com.example} that references
* {@code java.lang.String} will get {@code com.example.String} instead.
*/
public Builder skipJavaLangImports(boolean skipJavaLangImports) {
this.skipJavaLangImports = skipJavaLangImports;
return this;
}
public Builder indent(String indent) {
this.indent = indent;
return this;
}
public JavaFile build() {
return new JavaFile(this);
}
}
}
| 9,661 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
NameAllocator.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/NameAllocator.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkNotNull;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.openjdk.javax.lang.model.SourceVersion;
/**
* Assigns Java identifier names to avoid collisions, keywords, and invalid characters. To use,
* first create an instance and allocate all of the names that you need. Typically this is a mix of
* user-supplied names and constants:
*
* <pre>{@code
* NameAllocator nameAllocator = new NameAllocator();
* for (MyProperty property : properties) {
* nameAllocator.newName(property.name(), property);
* }
* nameAllocator.newName("sb", "string builder");
* }</pre>
*
* Pass a unique tag object to each allocation. The tag scopes the name, and can be used to look up
* the allocated name later. Typically the tag is the object that is being named. In the above
* example we use {@code property} for the user-supplied property names, and {@code "string
* builder"} for our constant string builder.
*
* <p>Once we've allocated names we can use them when generating code:
*
* <pre>{@code
* MethodSpec.Builder builder = MethodSpec.methodBuilder("toString")
* .addAnnotation(Override.class)
* .addModifiers(Modifier.PUBLIC)
* .returns(String.class);
*
* builder.addStatement("$1T $2N = new $1T()",
* StringBuilder.class, nameAllocator.get("string builder"));
* for (MyProperty property : properties) {
* builder.addStatement("$N.append($N)",
* nameAllocator.get("string builder"), nameAllocator.get(property));
* }
* builder.addStatement("return $N", nameAllocator.get("string builder"));
* return builder.build();
* }</pre>
*
* The above code generates unique names if presented with conflicts. Given user-supplied properties
* with names {@code ab} and {@code sb} this generates the following:
*
* <pre>{@code
* @Override
* public String toString() {
* StringBuilder sb_ = new StringBuilder();
* sb_.append(ab);
* sb_.append(sb);
* return sb_.toString();
* }
* }</pre>
*
* The underscore is appended to {@code sb} to avoid conflicting with the user-supplied {@code sb}
* property. Underscores are also prefixed for names that start with a digit, and used to replace
* name-unsafe characters like space or dash.
*
* <p>When dealing with multiple independent inner scopes, use a {@link #clone()} of the
* NameAllocator used for the outer scope to further refine name allocation for a specific inner
* scope.
*/
public final class NameAllocator implements Cloneable {
private final Set<String> allocatedNames;
private final Map<Object, String> tagToName;
public NameAllocator() {
this(new LinkedHashSet<String>(), new LinkedHashMap<Object, String>());
}
private NameAllocator(
LinkedHashSet<String> allocatedNames, LinkedHashMap<Object, String> tagToName) {
this.allocatedNames = allocatedNames;
this.tagToName = tagToName;
}
/**
* Return a new name using {@code suggestion} that will not be a Java identifier or clash with
* other names.
*/
public String newName(String suggestion) {
return newName(suggestion, UUID.randomUUID().toString());
}
/**
* Return a new name using {@code suggestion} that will not be a Java identifier or clash with
* other names. The returned value can be queried multiple times by passing {@code tag} to {@link
* #get(Object)}.
*/
public String newName(String suggestion, Object tag) {
checkNotNull(suggestion, "suggestion");
checkNotNull(tag, "tag");
suggestion = toJavaIdentifier(suggestion);
while (SourceVersion.isKeyword(suggestion) || !allocatedNames.add(suggestion)) {
suggestion = suggestion + "_";
}
String replaced = tagToName.put(tag, suggestion);
if (replaced != null) {
tagToName.put(tag, replaced); // Put things back as they were!
throw new IllegalArgumentException(
"tag " + tag + " cannot be used for both '" + replaced + "' and '" + suggestion + "'");
}
return suggestion;
}
public static String toJavaIdentifier(String suggestion) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < suggestion.length(); ) {
int codePoint = suggestion.codePointAt(i);
if (i == 0
&& !Character.isJavaIdentifierStart(codePoint)
&& Character.isJavaIdentifierPart(codePoint)) {
result.append("_");
}
int validCodePoint = Character.isJavaIdentifierPart(codePoint) ? codePoint : '_';
result.appendCodePoint(validCodePoint);
i += Character.charCount(codePoint);
}
return result.toString();
}
/** Retrieve a name created with {@link #newName(String, Object)}. */
public String get(Object tag) {
String result = tagToName.get(tag);
if (result == null) {
throw new IllegalArgumentException("unknown tag: " + tag);
}
return result;
}
/**
* Create a deep copy of this NameAllocator. Useful to create multiple independent refinements of
* a NameAllocator to be used in the respective definition of multiples, independently-scoped,
* inner code blocks.
*
* @return A deep copy of this NameAllocator.
*/
@Override
public NameAllocator clone() {
return new NameAllocator(
new LinkedHashSet<>(this.allocatedNames), new LinkedHashMap<>(this.tagToName));
}
}
| 6,029 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
TypeSpec.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/TypeSpec.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import static com.squareup.javapoet.Util.checkState;
import static com.squareup.javapoet.Util.hasDefaultModifier;
import static com.squareup.javapoet.Util.requireExactlyOneOf;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.openjdk.javax.lang.model.SourceVersion;
import org.openjdk.javax.lang.model.element.Element;
import org.openjdk.javax.lang.model.element.Modifier;
/** A generated class, interface, or enum declaration. */
public final class TypeSpec {
public final Kind kind;
public final String name;
public final CodeBlock anonymousTypeArguments;
public final CodeBlock javadoc;
public final List<AnnotationSpec> annotations;
public final Set<Modifier> modifiers;
public final List<TypeVariableName> typeVariables;
public final TypeName superclass;
public final List<TypeName> superinterfaces;
public final Map<String, TypeSpec> enumConstants;
public final List<FieldSpec> fieldSpecs;
public final CodeBlock staticBlock;
public final CodeBlock initializerBlock;
public final List<MethodSpec> methodSpecs;
public final List<TypeSpec> typeSpecs;
public final List<Element> originatingElements;
private TypeSpec(Builder builder) {
this.kind = builder.kind;
this.name = builder.name;
this.anonymousTypeArguments = builder.anonymousTypeArguments;
this.javadoc = builder.javadoc.build();
this.annotations = Util.immutableList(builder.annotations);
this.modifiers = Util.immutableSet(builder.modifiers);
this.typeVariables = Util.immutableList(builder.typeVariables);
this.superclass = builder.superclass;
this.superinterfaces = Util.immutableList(builder.superinterfaces);
this.enumConstants = Util.immutableMap(builder.enumConstants);
this.fieldSpecs = Util.immutableList(builder.fieldSpecs);
this.staticBlock = builder.staticBlock.build();
this.initializerBlock = builder.initializerBlock.build();
this.methodSpecs = Util.immutableList(builder.methodSpecs);
this.typeSpecs = Util.immutableList(builder.typeSpecs);
List<Element> originatingElementsMutable = new ArrayList<>();
originatingElementsMutable.addAll(builder.originatingElements);
for (TypeSpec typeSpec : builder.typeSpecs) {
originatingElementsMutable.addAll(typeSpec.originatingElements);
}
this.originatingElements = Util.immutableList(originatingElementsMutable);
}
/**
* Creates a dummy type spec for type-resolution only (in CodeWriter) while emitting the type
* declaration but before entering the type body.
*/
private TypeSpec(TypeSpec type) {
assert type.anonymousTypeArguments == null;
this.kind = type.kind;
this.name = type.name;
this.anonymousTypeArguments = null;
this.javadoc = type.javadoc;
this.annotations = Collections.emptyList();
this.modifiers = Collections.emptySet();
this.typeVariables = Collections.emptyList();
this.superclass = null;
this.superinterfaces = Collections.emptyList();
this.enumConstants = Collections.emptyMap();
this.fieldSpecs = Collections.emptyList();
this.staticBlock = type.staticBlock;
this.initializerBlock = type.initializerBlock;
this.methodSpecs = Collections.emptyList();
this.typeSpecs = Collections.emptyList();
this.originatingElements = Collections.emptyList();
}
public boolean hasModifier(Modifier modifier) {
return modifiers.contains(modifier);
}
public static Builder classBuilder(String name) {
return new Builder(Kind.CLASS, checkNotNull(name, "name == null"), null);
}
public static Builder classBuilder(ClassName className) {
return classBuilder(checkNotNull(className, "className == null").simpleName());
}
public static Builder interfaceBuilder(String name) {
return new Builder(Kind.INTERFACE, checkNotNull(name, "name == null"), null);
}
public static Builder interfaceBuilder(ClassName className) {
return interfaceBuilder(checkNotNull(className, "className == null").simpleName());
}
public static Builder enumBuilder(String name) {
return new Builder(Kind.ENUM, checkNotNull(name, "name == null"), null);
}
public static Builder enumBuilder(ClassName className) {
return enumBuilder(checkNotNull(className, "className == null").simpleName());
}
public static Builder anonymousClassBuilder(String typeArgumentsFormat, Object... args) {
return anonymousClassBuilder(CodeBlock.builder().add(typeArgumentsFormat, args).build());
}
public static Builder anonymousClassBuilder(CodeBlock typeArguments) {
return new Builder(Kind.CLASS, null, typeArguments);
}
public static Builder annotationBuilder(String name) {
return new Builder(Kind.ANNOTATION, checkNotNull(name, "name == null"), null);
}
public static Builder annotationBuilder(ClassName className) {
return annotationBuilder(checkNotNull(className, "className == null").simpleName());
}
public Builder toBuilder() {
Builder builder = new Builder(kind, name, anonymousTypeArguments);
builder.javadoc.add(javadoc);
builder.annotations.addAll(annotations);
builder.modifiers.addAll(modifiers);
builder.typeVariables.addAll(typeVariables);
builder.superclass = superclass;
builder.superinterfaces.addAll(superinterfaces);
builder.enumConstants.putAll(enumConstants);
builder.fieldSpecs.addAll(fieldSpecs);
builder.methodSpecs.addAll(methodSpecs);
builder.typeSpecs.addAll(typeSpecs);
builder.initializerBlock.add(initializerBlock);
builder.staticBlock.add(staticBlock);
return builder;
}
void emit(CodeWriter codeWriter, String enumName, Set<Modifier> implicitModifiers)
throws IOException {
// Nested classes interrupt wrapped line indentation. Stash the current wrapping state and put
// it back afterwards when this type is complete.
int previousStatementLine = codeWriter.statementLine;
codeWriter.statementLine = -1;
try {
if (enumName != null) {
codeWriter.emitJavadoc(javadoc);
codeWriter.emitAnnotations(annotations, false);
codeWriter.emit("$L", enumName);
if (!anonymousTypeArguments.formatParts.isEmpty()) {
codeWriter.emit("(");
codeWriter.emit(anonymousTypeArguments);
codeWriter.emit(")");
}
if (fieldSpecs.isEmpty() && methodSpecs.isEmpty() && typeSpecs.isEmpty()) {
return; // Avoid unnecessary braces "{}".
}
codeWriter.emit(" {\n");
} else if (anonymousTypeArguments != null) {
TypeName supertype = !superinterfaces.isEmpty() ? superinterfaces.get(0) : superclass;
codeWriter.emit("new $T(", supertype);
codeWriter.emit(anonymousTypeArguments);
codeWriter.emit(") {\n");
} else {
// Push an empty type (specifically without nested types) for type-resolution.
codeWriter.pushType(new TypeSpec(this));
codeWriter.emitJavadoc(javadoc);
codeWriter.emitAnnotations(annotations, false);
codeWriter.emitModifiers(modifiers, Util.union(implicitModifiers, kind.asMemberModifiers));
if (kind == Kind.ANNOTATION) {
codeWriter.emit("$L $L", "@interface", name);
} else {
codeWriter.emit("$L $L", kind.name().toLowerCase(Locale.US), name);
}
codeWriter.emitTypeVariables(typeVariables);
List<TypeName> extendsTypes;
List<TypeName> implementsTypes;
if (kind == Kind.INTERFACE) {
extendsTypes = superinterfaces;
implementsTypes = Collections.emptyList();
} else {
extendsTypes =
superclass.equals(ClassName.OBJECT)
? Collections.<TypeName>emptyList()
: Collections.singletonList(superclass);
implementsTypes = superinterfaces;
}
if (!extendsTypes.isEmpty()) {
codeWriter.emit(" extends");
boolean firstType = true;
for (TypeName type : extendsTypes) {
if (!firstType) codeWriter.emit(",");
codeWriter.emit(" $T", type);
firstType = false;
}
}
if (!implementsTypes.isEmpty()) {
codeWriter.emit(" implements");
boolean firstType = true;
for (TypeName type : implementsTypes) {
if (!firstType) codeWriter.emit(",");
codeWriter.emit(" $T", type);
firstType = false;
}
}
codeWriter.popType();
codeWriter.emit(" {\n");
}
codeWriter.pushType(this);
codeWriter.indent();
boolean firstMember = true;
for (Iterator<Map.Entry<String, TypeSpec>> i = enumConstants.entrySet().iterator();
i.hasNext(); ) {
Map.Entry<String, TypeSpec> enumConstant = i.next();
if (!firstMember) codeWriter.emit("\n");
enumConstant
.getValue()
.emit(codeWriter, enumConstant.getKey(), Collections.<Modifier>emptySet());
firstMember = false;
if (i.hasNext()) {
codeWriter.emit(",\n");
} else if (!fieldSpecs.isEmpty() || !methodSpecs.isEmpty() || !typeSpecs.isEmpty()) {
codeWriter.emit(";\n");
} else {
codeWriter.emit("\n");
}
}
// Static fields.
for (FieldSpec fieldSpec : fieldSpecs) {
if (!fieldSpec.hasModifier(Modifier.STATIC)) continue;
if (!firstMember) codeWriter.emit("\n");
fieldSpec.emit(codeWriter, kind.implicitFieldModifiers);
firstMember = false;
}
if (!staticBlock.isEmpty()) {
if (!firstMember) codeWriter.emit("\n");
codeWriter.emit(staticBlock);
firstMember = false;
}
// Non-static fields.
for (FieldSpec fieldSpec : fieldSpecs) {
if (fieldSpec.hasModifier(Modifier.STATIC)) continue;
if (!firstMember) codeWriter.emit("\n");
fieldSpec.emit(codeWriter, kind.implicitFieldModifiers);
firstMember = false;
}
// Initializer block.
if (!initializerBlock.isEmpty()) {
if (!firstMember) codeWriter.emit("\n");
codeWriter.emit(initializerBlock);
firstMember = false;
}
// Constructors.
for (MethodSpec methodSpec : methodSpecs) {
if (!methodSpec.isConstructor()) continue;
if (!firstMember) codeWriter.emit("\n");
methodSpec.emit(codeWriter, name, kind.implicitMethodModifiers);
firstMember = false;
}
// Methods (static and non-static).
for (MethodSpec methodSpec : methodSpecs) {
if (methodSpec.isConstructor()) continue;
if (!firstMember) codeWriter.emit("\n");
methodSpec.emit(codeWriter, name, kind.implicitMethodModifiers);
firstMember = false;
}
// Types.
for (TypeSpec typeSpec : typeSpecs) {
if (!firstMember) codeWriter.emit("\n");
typeSpec.emit(codeWriter, null, kind.implicitTypeModifiers);
firstMember = false;
}
codeWriter.unindent();
codeWriter.popType();
codeWriter.emit("}");
if (enumName == null && anonymousTypeArguments == null) {
codeWriter.emit("\n"); // If this type isn't also a value, include a trailing newline.
}
} finally {
codeWriter.statementLine = previousStatementLine;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (getClass() != o.getClass()) return false;
return toString().equals(o.toString());
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public String toString() {
StringBuilder out = new StringBuilder();
try {
CodeWriter codeWriter = new CodeWriter(out);
emit(codeWriter, null, Collections.<Modifier>emptySet());
return out.toString();
} catch (IOException e) {
throw new AssertionError();
}
}
public enum Kind {
CLASS(
Collections.<Modifier>emptySet(),
Collections.<Modifier>emptySet(),
Collections.<Modifier>emptySet(),
Collections.<Modifier>emptySet()),
INTERFACE(
Util.immutableSet(Arrays.asList(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)),
Util.immutableSet(Arrays.asList(Modifier.PUBLIC, Modifier.ABSTRACT)),
Util.immutableSet(Arrays.asList(Modifier.PUBLIC, Modifier.STATIC)),
Util.immutableSet(Arrays.asList(Modifier.STATIC))),
ENUM(
Collections.<Modifier>emptySet(),
Collections.<Modifier>emptySet(),
Collections.<Modifier>emptySet(),
Collections.singleton(Modifier.STATIC)),
ANNOTATION(
Util.immutableSet(Arrays.asList(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)),
Util.immutableSet(Arrays.asList(Modifier.PUBLIC, Modifier.ABSTRACT)),
Util.immutableSet(Arrays.asList(Modifier.PUBLIC, Modifier.STATIC)),
Util.immutableSet(Arrays.asList(Modifier.STATIC)));
private final Set<Modifier> implicitFieldModifiers;
private final Set<Modifier> implicitMethodModifiers;
private final Set<Modifier> implicitTypeModifiers;
private final Set<Modifier> asMemberModifiers;
Kind(
Set<Modifier> implicitFieldModifiers,
Set<Modifier> implicitMethodModifiers,
Set<Modifier> implicitTypeModifiers,
Set<Modifier> asMemberModifiers) {
this.implicitFieldModifiers = implicitFieldModifiers;
this.implicitMethodModifiers = implicitMethodModifiers;
this.implicitTypeModifiers = implicitTypeModifiers;
this.asMemberModifiers = asMemberModifiers;
}
}
public static final class Builder {
private final Kind kind;
private final String name;
private final CodeBlock anonymousTypeArguments;
private final CodeBlock.Builder javadoc = CodeBlock.builder();
private final List<AnnotationSpec> annotations = new ArrayList<>();
private final List<Modifier> modifiers = new ArrayList<>();
private final List<TypeVariableName> typeVariables = new ArrayList<>();
private TypeName superclass = ClassName.OBJECT;
private final List<TypeName> superinterfaces = new ArrayList<>();
private final Map<String, TypeSpec> enumConstants = new LinkedHashMap<>();
private final List<FieldSpec> fieldSpecs = new ArrayList<>();
private final CodeBlock.Builder staticBlock = CodeBlock.builder();
private final CodeBlock.Builder initializerBlock = CodeBlock.builder();
private final List<MethodSpec> methodSpecs = new ArrayList<>();
private final List<TypeSpec> typeSpecs = new ArrayList<>();
private final List<Element> originatingElements = new ArrayList<>();
private Builder(Kind kind, String name, CodeBlock anonymousTypeArguments) {
checkArgument(name == null || SourceVersion.isName(name), "not a valid name: %s", name);
this.kind = kind;
this.name = name;
this.anonymousTypeArguments = anonymousTypeArguments;
}
public Builder addJavadoc(String format, Object... args) {
javadoc.add(format, args);
return this;
}
public Builder addJavadoc(CodeBlock block) {
javadoc.add(block);
return this;
}
public Builder addAnnotations(Iterable<AnnotationSpec> annotationSpecs) {
checkArgument(annotationSpecs != null, "annotationSpecs == null");
for (AnnotationSpec annotationSpec : annotationSpecs) {
this.annotations.add(annotationSpec);
}
return this;
}
public Builder addAnnotation(AnnotationSpec annotationSpec) {
this.annotations.add(annotationSpec);
return this;
}
public Builder addAnnotation(ClassName annotation) {
return addAnnotation(AnnotationSpec.builder(annotation).build());
}
public Builder addAnnotation(Class<?> annotation) {
return addAnnotation(ClassName.get(annotation));
}
public Builder addModifiers(Modifier... modifiers) {
checkState(anonymousTypeArguments == null, "forbidden on anonymous types.");
for (Modifier modifier : modifiers) {
checkArgument(modifier != null, "modifiers contain null");
this.modifiers.add(modifier);
}
return this;
}
public Builder addTypeVariables(Iterable<TypeVariableName> typeVariables) {
checkState(anonymousTypeArguments == null, "forbidden on anonymous types.");
checkArgument(typeVariables != null, "typeVariables == null");
for (TypeVariableName typeVariable : typeVariables) {
this.typeVariables.add(typeVariable);
}
return this;
}
public Builder addTypeVariable(TypeVariableName typeVariable) {
checkState(anonymousTypeArguments == null, "forbidden on anonymous types.");
typeVariables.add(typeVariable);
return this;
}
public Builder superclass(TypeName superclass) {
checkState(this.kind == Kind.CLASS, "only classes have super classes, not " + this.kind);
checkState(
this.superclass == ClassName.OBJECT, "superclass already set to " + this.superclass);
checkArgument(!superclass.isPrimitive(), "superclass may not be a primitive");
this.superclass = superclass;
return this;
}
public Builder superclass(Type superclass) {
return superclass(TypeName.get(superclass));
}
public Builder addSuperinterfaces(Iterable<? extends TypeName> superinterfaces) {
checkArgument(superinterfaces != null, "superinterfaces == null");
for (TypeName superinterface : superinterfaces) {
addSuperinterface(superinterface);
}
return this;
}
public Builder addSuperinterface(TypeName superinterface) {
checkArgument(superinterface != null, "superinterface == null");
this.superinterfaces.add(superinterface);
return this;
}
public Builder addSuperinterface(Type superinterface) {
return addSuperinterface(TypeName.get(superinterface));
}
public Builder addEnumConstant(String name) {
return addEnumConstant(name, anonymousClassBuilder("").build());
}
public Builder addEnumConstant(String name, TypeSpec typeSpec) {
checkState(kind == Kind.ENUM, "%s is not enum", this.name);
checkArgument(
typeSpec.anonymousTypeArguments != null,
"enum constants must have anonymous type arguments");
checkArgument(SourceVersion.isName(name), "not a valid enum constant: %s", name);
enumConstants.put(name, typeSpec);
return this;
}
public Builder addFields(Iterable<FieldSpec> fieldSpecs) {
checkArgument(fieldSpecs != null, "fieldSpecs == null");
for (FieldSpec fieldSpec : fieldSpecs) {
addField(fieldSpec);
}
return this;
}
public Builder addField(FieldSpec fieldSpec) {
if (kind == Kind.INTERFACE || kind == Kind.ANNOTATION) {
requireExactlyOneOf(fieldSpec.modifiers, Modifier.PUBLIC, Modifier.PRIVATE);
Set<Modifier> check = EnumSet.of(Modifier.STATIC, Modifier.FINAL);
checkState(
fieldSpec.modifiers.containsAll(check),
"%s %s.%s requires modifiers %s",
kind,
name,
fieldSpec.name,
check);
}
fieldSpecs.add(fieldSpec);
return this;
}
public Builder addField(TypeName type, String name, Modifier... modifiers) {
return addField(FieldSpec.builder(type, name, modifiers).build());
}
public Builder addField(Type type, String name, Modifier... modifiers) {
return addField(TypeName.get(type), name, modifiers);
}
public Builder addStaticBlock(CodeBlock block) {
staticBlock.beginControlFlow("static").add(block).endControlFlow();
return this;
}
public Builder addInitializerBlock(CodeBlock block) {
if ((kind != Kind.CLASS && kind != Kind.ENUM)) {
throw new UnsupportedOperationException(kind + " can't have initializer blocks");
}
initializerBlock.add("{\n").indent().add(block).unindent().add("}\n");
return this;
}
public Builder addMethods(Iterable<MethodSpec> methodSpecs) {
checkArgument(methodSpecs != null, "methodSpecs == null");
for (MethodSpec methodSpec : methodSpecs) {
addMethod(methodSpec);
}
return this;
}
public Builder addMethod(MethodSpec methodSpec) {
if (kind == Kind.INTERFACE) {
requireExactlyOneOf(methodSpec.modifiers, Modifier.ABSTRACT, Modifier.STATIC, Util.DEFAULT);
requireExactlyOneOf(methodSpec.modifiers, Modifier.PUBLIC, Modifier.PRIVATE);
} else if (kind == Kind.ANNOTATION) {
checkState(
methodSpec.modifiers.equals(kind.implicitMethodModifiers),
"%s %s.%s requires modifiers %s",
kind,
name,
methodSpec.name,
kind.implicitMethodModifiers);
}
if (kind != Kind.ANNOTATION) {
checkState(
methodSpec.defaultValue == null,
"%s %s.%s cannot have a default value",
kind,
name,
methodSpec.name);
}
if (kind != Kind.INTERFACE) {
checkState(
!hasDefaultModifier(methodSpec.modifiers),
"%s %s.%s cannot be default",
kind,
name,
methodSpec.name);
}
methodSpecs.add(methodSpec);
return this;
}
public Builder addTypes(Iterable<TypeSpec> typeSpecs) {
checkArgument(typeSpecs != null, "typeSpecs == null");
for (TypeSpec typeSpec : typeSpecs) {
addType(typeSpec);
}
return this;
}
public Builder addType(TypeSpec typeSpec) {
checkArgument(
typeSpec.modifiers.containsAll(kind.implicitTypeModifiers),
"%s %s.%s requires modifiers %s",
kind,
name,
typeSpec.name,
kind.implicitTypeModifiers);
typeSpecs.add(typeSpec);
return this;
}
public Builder addOriginatingElement(Element originatingElement) {
originatingElements.add(originatingElement);
return this;
}
public TypeSpec build() {
checkArgument(
kind != Kind.ENUM || !enumConstants.isEmpty(),
"at least one enum constant is required for %s",
name);
boolean isAbstract = modifiers.contains(Modifier.ABSTRACT) || kind != Kind.CLASS;
for (MethodSpec methodSpec : methodSpecs) {
checkArgument(
isAbstract || !methodSpec.hasModifier(Modifier.ABSTRACT),
"non-abstract type %s cannot declare abstract method %s",
name,
methodSpec.name);
}
boolean superclassIsObject = superclass.equals(ClassName.OBJECT);
int interestingSupertypeCount = (superclassIsObject ? 0 : 1) + superinterfaces.size();
checkArgument(
anonymousTypeArguments == null || interestingSupertypeCount <= 1,
"anonymous type has too many supertypes");
return new TypeSpec(this);
}
}
}
| 23,978 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CodeWriter.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/javapoet/src/main/java/com/squareup/javapoet/CodeWriter.java | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.javapoet;
import static com.squareup.javapoet.Util.checkArgument;
import static com.squareup.javapoet.Util.checkNotNull;
import static com.squareup.javapoet.Util.checkState;
import static com.squareup.javapoet.Util.join;
import static com.squareup.javapoet.Util.stringLiteralWithDoubleQuotes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.openjdk.javax.lang.model.SourceVersion;
import org.openjdk.javax.lang.model.element.Modifier;
/**
* Converts a {@link JavaFile} to a string suitable to both human- and javac-consumption. This
* honors imports, indentation, and deferred variable names.
*/
final class CodeWriter {
/** Sentinel value that indicates that no user-provided package has been set. */
private static final String NO_PACKAGE = new String();
private final String indent;
private final LineWrapper out;
private int indentLevel;
private boolean javadoc = false;
private boolean comment = false;
private String packageName = NO_PACKAGE;
private final List<TypeSpec> typeSpecStack = new ArrayList<>();
private final Set<String> staticImportClassNames;
private final Set<String> staticImports;
private final Map<String, ClassName> importedTypes;
private final Map<String, ClassName> importableTypes = new LinkedHashMap<>();
private final Set<String> referencedNames = new LinkedHashSet<>();
private boolean trailingNewline;
/**
* When emitting a statement, this is the line of the statement currently being written. The first
* line of a statement is indented normally and subsequent wrapped lines are double-indented. This
* is -1 when the currently-written line isn't part of a statement.
*/
int statementLine = -1;
CodeWriter(Appendable out) {
this(out, " ", Collections.<String>emptySet());
}
CodeWriter(Appendable out, String indent, Set<String> staticImports) {
this(out, indent, Collections.<String, ClassName>emptyMap(), staticImports);
}
CodeWriter(
Appendable out,
String indent,
Map<String, ClassName> importedTypes,
Set<String> staticImports) {
this.out = new LineWrapper(out, indent, 100);
this.indent = checkNotNull(indent, "indent == null");
this.importedTypes = checkNotNull(importedTypes, "importedTypes == null");
this.staticImports = checkNotNull(staticImports, "staticImports == null");
this.staticImportClassNames = new LinkedHashSet<>();
for (String signature : staticImports) {
staticImportClassNames.add(signature.substring(0, signature.lastIndexOf('.')));
}
}
public Map<String, ClassName> importedTypes() {
return importedTypes;
}
public CodeWriter indent() {
return indent(1);
}
public CodeWriter indent(int levels) {
indentLevel += levels;
return this;
}
public CodeWriter unindent() {
return unindent(1);
}
public CodeWriter unindent(int levels) {
checkArgument(indentLevel - levels >= 0, "cannot unindent %s from %s", levels, indentLevel);
indentLevel -= levels;
return this;
}
public CodeWriter pushPackage(String packageName) {
checkState(this.packageName == NO_PACKAGE, "package already set: %s", this.packageName);
this.packageName = checkNotNull(packageName, "packageName == null");
return this;
}
public CodeWriter popPackage() {
checkState(this.packageName != NO_PACKAGE, "package already set: %s", this.packageName);
this.packageName = NO_PACKAGE;
return this;
}
public CodeWriter pushType(TypeSpec type) {
this.typeSpecStack.add(type);
return this;
}
public CodeWriter popType() {
this.typeSpecStack.remove(typeSpecStack.size() - 1);
return this;
}
public void emitComment(CodeBlock codeBlock) throws IOException {
trailingNewline = true; // Force the '//' prefix for the comment.
comment = true;
try {
emit(codeBlock);
emit("\n");
} finally {
comment = false;
}
}
public void emitJavadoc(CodeBlock javadocCodeBlock) throws IOException {
if (javadocCodeBlock.isEmpty()) return;
emit("/**\n");
javadoc = true;
try {
emit(javadocCodeBlock);
} finally {
javadoc = false;
}
emit(" */\n");
}
public void emitAnnotations(List<AnnotationSpec> annotations, boolean inline) throws IOException {
for (AnnotationSpec annotationSpec : annotations) {
annotationSpec.emit(this, inline);
emit(inline ? " " : "\n");
}
}
/**
* Emits {@code modifiers} in the standard order. Modifiers in {@code implicitModifiers} will not
* be emitted.
*/
public void emitModifiers(Set<Modifier> modifiers, Set<Modifier> implicitModifiers)
throws IOException {
if (modifiers.isEmpty()) return;
for (Modifier modifier : EnumSet.copyOf(modifiers)) {
if (implicitModifiers.contains(modifier)) continue;
emitAndIndent(modifier.name().toLowerCase(Locale.US));
emitAndIndent(" ");
}
}
public void emitModifiers(Set<Modifier> modifiers) throws IOException {
emitModifiers(modifiers, Collections.<Modifier>emptySet());
}
/**
* Emit type variables with their bounds. This should only be used when declaring type variables;
* everywhere else bounds are omitted.
*/
public void emitTypeVariables(List<TypeVariableName> typeVariables) throws IOException {
if (typeVariables.isEmpty()) return;
emit("<");
boolean firstTypeVariable = true;
for (TypeVariableName typeVariable : typeVariables) {
if (!firstTypeVariable) emit(", ");
emitAnnotations(typeVariable.annotations, true);
emit("$L", typeVariable.name);
boolean firstBound = true;
for (TypeName bound : typeVariable.bounds) {
emit(firstBound ? " extends $T" : " & $T", bound);
firstBound = false;
}
firstTypeVariable = false;
}
emit(">");
}
public CodeWriter emit(String s) throws IOException {
return emitAndIndent(s);
}
public CodeWriter emit(String format, Object... args) throws IOException {
return emit(CodeBlock.of(format, args));
}
public CodeWriter emit(CodeBlock codeBlock) throws IOException {
int a = 0;
ClassName deferredTypeName = null; // used by "import static" logic
ListIterator<String> partIterator = codeBlock.formatParts.listIterator();
while (partIterator.hasNext()) {
String part = partIterator.next();
switch (part) {
case "$L":
emitLiteral(codeBlock.args.get(a++));
break;
case "$N":
emitAndIndent((String) codeBlock.args.get(a++));
break;
case "$S":
String string = (String) codeBlock.args.get(a++);
// Emit null as a literal null: no quotes.
emitAndIndent(string != null ? stringLiteralWithDoubleQuotes(string, indent) : "null");
break;
case "$T":
TypeName typeName = (TypeName) codeBlock.args.get(a++);
if (typeName.isAnnotated()) {
typeName.emitAnnotations(this);
typeName = typeName.withoutAnnotations();
}
// defer "typeName.emit(this)" if next format part will be handled by the default case
if (typeName instanceof ClassName && partIterator.hasNext()) {
if (!codeBlock.formatParts.get(partIterator.nextIndex()).startsWith("$")) {
ClassName candidate = (ClassName) typeName;
if (staticImportClassNames.contains(candidate.canonicalName)) {
checkState(deferredTypeName == null, "pending type for static import?!");
deferredTypeName = candidate;
break;
}
}
}
typeName.emit(this);
break;
case "$$":
emitAndIndent("$");
break;
case "$>":
indent();
break;
case "$<":
unindent();
break;
case "$[":
checkState(statementLine == -1, "statement enter $[ followed by statement enter $[");
statementLine = 0;
break;
case "$]":
checkState(statementLine != -1, "statement exit $] has no matching statement enter $[");
if (statementLine > 0) {
unindent(2); // End a multi-line statement. Decrease the indentation level.
}
statementLine = -1;
break;
case "$W":
out.wrappingSpace(indentLevel + 2);
break;
case "$Z":
out.zeroWidthSpace(indentLevel + 2);
break;
default:
// handle deferred type
if (deferredTypeName != null) {
if (part.startsWith(".")) {
if (emitStaticImportMember(deferredTypeName.canonicalName, part)) {
// okay, static import hit and all was emitted, so clean-up and jump to next part
deferredTypeName = null;
break;
}
}
deferredTypeName.emit(this);
deferredTypeName = null;
}
emitAndIndent(part);
break;
}
}
return this;
}
public CodeWriter emitWrappingSpace() throws IOException {
out.wrappingSpace(indentLevel + 2);
return this;
}
private static String extractMemberName(String part) {
checkArgument(Character.isJavaIdentifierStart(part.charAt(0)), "not an identifier: %s", part);
for (int i = 1; i <= part.length(); i++) {
if (!SourceVersion.isIdentifier(part.substring(0, i))) {
return part.substring(0, i - 1);
}
}
return part;
}
private boolean emitStaticImportMember(String canonical, String part) throws IOException {
String partWithoutLeadingDot = part.substring(1);
if (partWithoutLeadingDot.isEmpty()) return false;
char first = partWithoutLeadingDot.charAt(0);
if (!Character.isJavaIdentifierStart(first)) return false;
String explicit = canonical + "." + extractMemberName(partWithoutLeadingDot);
String wildcard = canonical + ".*";
if (staticImports.contains(explicit) || staticImports.contains(wildcard)) {
emitAndIndent(partWithoutLeadingDot);
return true;
}
return false;
}
private void emitLiteral(Object o) throws IOException {
if (o instanceof TypeSpec) {
TypeSpec typeSpec = (TypeSpec) o;
typeSpec.emit(this, null, Collections.<Modifier>emptySet());
} else if (o instanceof AnnotationSpec) {
AnnotationSpec annotationSpec = (AnnotationSpec) o;
annotationSpec.emit(this, true);
} else if (o instanceof CodeBlock) {
CodeBlock codeBlock = (CodeBlock) o;
emit(codeBlock);
} else {
emitAndIndent(String.valueOf(o));
}
}
/**
* Returns the best name to identify {@code className} with in the current context. This uses the
* available imports and the current scope to find the shortest name available. It does not honor
* names visible due to inheritance.
*/
String lookupName(ClassName className) {
// Find the shortest suffix of className that resolves to className. This uses both local type
// names (so `Entry` in `Map` refers to `Map.Entry`). Also uses imports.
boolean nameResolved = false;
for (ClassName c = className; c != null; c = c.enclosingClassName()) {
ClassName resolved = resolve(c.simpleName());
nameResolved = resolved != null;
if (resolved != null && Objects.equals(resolved.canonicalName, c.canonicalName)) {
int suffixOffset = c.simpleNames().size() - 1;
return join(
".", className.simpleNames().subList(suffixOffset, className.simpleNames().size()));
}
}
// If the name resolved but wasn't a match, we're stuck with the fully qualified name.
if (nameResolved) {
return className.canonicalName;
}
// If the class is in the same package, we're done.
if (Objects.equals(packageName, className.packageName())) {
referencedNames.add(className.topLevelClassName().simpleName());
return join(".", className.simpleNames());
}
// We'll have to use the fully-qualified name. Mark the type as importable for a future pass.
if (!javadoc) {
importableType(className);
}
return className.canonicalName;
}
private void importableType(ClassName className) {
if (className.packageName().isEmpty()) {
return;
}
ClassName topLevelClassName = className.topLevelClassName();
String simpleName = topLevelClassName.simpleName();
ClassName replaced = importableTypes.put(simpleName, topLevelClassName);
if (replaced != null) {
importableTypes.put(simpleName, replaced); // On collision, prefer the first inserted.
}
}
/**
* Returns the class referenced by {@code simpleName}, using the current nesting context and
* imports.
*/
// TODO(jwilson): also honor superclass members when resolving names.
private ClassName resolve(String simpleName) {
// Match a child of the current (potentially nested) class.
for (int i = typeSpecStack.size() - 1; i >= 0; i--) {
TypeSpec typeSpec = typeSpecStack.get(i);
for (TypeSpec visibleChild : typeSpec.typeSpecs) {
if (Objects.equals(visibleChild.name, simpleName)) {
return stackClassName(i, simpleName);
}
}
}
// Match the top-level class.
if (typeSpecStack.size() > 0 && Objects.equals(typeSpecStack.get(0).name, simpleName)) {
return ClassName.get(packageName, simpleName);
}
// Match an imported type.
ClassName importedType = importedTypes.get(simpleName);
if (importedType != null) return importedType;
// No match.
return null;
}
/** Returns the class named {@code simpleName} when nested in the class at {@code stackDepth}. */
private ClassName stackClassName(int stackDepth, String simpleName) {
ClassName className = ClassName.get(packageName, typeSpecStack.get(0).name);
for (int i = 1; i <= stackDepth; i++) {
className = className.nestedClass(typeSpecStack.get(i).name);
}
return className.nestedClass(simpleName);
}
/**
* Emits {@code s} with indentation as required. It's important that all code that writes to
* {@link #out} does it through here, since we emit indentation lazily in order to avoid
* unnecessary trailing whitespace.
*/
CodeWriter emitAndIndent(String s) throws IOException {
boolean first = true;
for (String line : s.split("\n", -1)) {
// Emit a newline character. Make sure blank lines in Javadoc & comments look good.
if (!first) {
if ((javadoc || comment) && trailingNewline) {
emitIndentation();
out.append(javadoc ? " *" : "//");
}
out.append("\n");
trailingNewline = true;
if (statementLine != -1) {
if (statementLine == 0) {
indent(2); // Begin multiple-line statement. Increase the indentation level.
}
statementLine++;
}
}
first = false;
if (line.isEmpty()) continue; // Don't indent empty lines.
// Emit indentation and comment prefix if necessary.
if (trailingNewline) {
emitIndentation();
if (javadoc) {
out.append(" * ");
} else if (comment) {
out.append("// ");
}
}
out.append(line);
trailingNewline = false;
}
return this;
}
private void emitIndentation() throws IOException {
for (int j = 0; j < indentLevel; j++) {
out.append(indent);
}
}
/**
* Returns the types that should have been imported for this code. If there were any simple name
* collisions, that type's first use is imported.
*/
Map<String, ClassName> suggestedImports() {
Map<String, ClassName> result = new LinkedHashMap<>(importableTypes);
result.keySet().removeAll(referencedNames);
return result;
}
}
| 16,761 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AnAction.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/AnAction.java | package com.tyron.actions;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.function.Supplier;
/**
* Represents a menu that can be performed.
*
* <p>For an action to do something, override the {@link AnAction#actionPerformed(AnActionEvent)}
* and optionally override {@link AnAction#update(AnActionEvent)}. By implementing the {@link
* AnAction#update(AnActionEvent)} method, you can dynamically change the action's presentation
* depending on the place. For more information on places see {@link ActionPlaces}
*
* <pre>
* public class MyAction extends AnAction {
* public MyAction() {
* // ...
* }
*
* public void update(AnActionEvent e) {
* Presentation presentation = e.getPresentation();
* presentation.setVisible(true);
* presentation.setText(e.getPlace());
* }
*
* public void actionPerformed(AnActionEvent e) {
* // do something when this action is pressed
* }
* }
* </pre>
*
* This implementation is partially adopted from IntelliJ's Actions API.
*
* @see AnActionEvent
* @see Presentation
* @see ActionPlaces
*/
public abstract class AnAction {
private Presentation mTemplatePresentation;
public AnAction() {}
public AnAction(Drawable icon) {
this(Presentation.NULL_STRING, Presentation.NULL_STRING, icon);
}
public AnAction(@Nullable String text) {
this(text, null, null);
}
public AnAction(@NonNull Supplier<String> dynamicText) {
this(dynamicText, Presentation.NULL_STRING, null);
}
public AnAction(@Nullable String text, @Nullable String description, @Nullable Drawable icon) {
this(() -> text, () -> description, icon);
}
public AnAction(@NonNull Supplier<String> dynamicText, @Nullable Drawable icon) {
this(dynamicText, Presentation.NULL_STRING, icon);
}
public AnAction(
@NonNull Supplier<String> dynamicText,
@NonNull Supplier<String> description,
@Nullable Drawable icon) {
Presentation presentation = getTemplatePresentation();
presentation.setText(dynamicText);
presentation.setDescription(description);
presentation.setIcon(icon);
}
public final Presentation getTemplatePresentation() {
if (mTemplatePresentation == null) {
mTemplatePresentation = createTemplatePresentation();
}
return mTemplatePresentation;
}
private Presentation createTemplatePresentation() {
return Presentation.createTemplatePresentation();
}
public boolean displayTextInToolbar() {
return false;
}
public boolean useSmallerFontForTextInToolbar() {
return false;
}
/**
* Updates the state of this action. Default implementation does nothing. Override this method to
* provide the ability to dynamically change action's state and(or) presentation depending on the
* context. (For example when your action state depends on the selection you can check for the
* selection and change the state accordingly.)
*
* <p>This method can be called frequently and on UI thread. This means that this method is
* supposed to work really fast, no work should be done at this phase. For example checking values
* such as editor selection is fine but working with the file system such as reading/writing to a
* file is not. If the action state cannot be determined, do the checks in {@link
* #actionPerformed(AnActionEvent)} and inform the user if the action cannot be performed by
* possibly showing a dialog.
*
* @param event Carries information on the invocation place and data available
*/
public void update(@NonNull AnActionEvent event) {}
/**
* Implement this method to handle when this action has been clicked or pressed.
*
* @param e Carries information on the invocation place and data available.
*/
public abstract void actionPerformed(@NonNull AnActionEvent e);
public void beforeActionPerformedUpdate(@NonNull AnActionEvent e) {
update(e);
}
public String getTemplateText() {
return getTemplatePresentation().getText();
}
}
| 4,170 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AnActionEvent.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/AnActionEvent.java | package com.tyron.actions;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import org.jetbrains.kotlin.com.intellij.openapi.util.Key;
/**
* Container for information necessary to execute or update an {@link AnAction}
*
* @see AnAction#update(AnActionEvent)
* @see AnAction#actionPerformed(AnActionEvent)
*/
public class AnActionEvent implements PlaceProvider {
private final DataContext mDataContext;
private final String mPlace;
private Presentation mPresentation;
private final boolean mIsContextMenuAction;
private final boolean mIsActionToolbar;
public AnActionEvent(
@NonNull DataContext context,
@NonNull String place,
@NonNull Presentation presentation,
boolean isContextMenuAction,
boolean isActionToolbar) {
mDataContext = context;
mPlace = place;
mPresentation = presentation;
mIsContextMenuAction = isContextMenuAction;
mIsActionToolbar = isActionToolbar;
}
public void setPresentation(Presentation presentation) {
mPresentation = presentation;
}
@Override
public String getPlace() {
return mPlace;
}
public Presentation getPresentation() {
return mPresentation;
}
public boolean isContextMenuAction() {
return mIsContextMenuAction;
}
public boolean isActionToolbar() {
return mIsActionToolbar;
}
@Nullable
public <T> T getData(Key<T> key) {
return mDataContext.getData(key);
}
/**
* Returns a non null data by a data key. This method assumes that data has been checked for
* {@code null} in {@code AnAction#update} method. <br>
* <br>
* Example of proper usage:
*
* <pre>
* public class MyAction extends AnAction {
* public void update(AnActionEvent e) {
* // perform action if and only if EDITOR != null
* boolean visible = e.getData(CommonDataKeys.EDITOR) != null;
* e.getPresentation().setVisible(visible);
* }
*
* public void actionPerformed(AnActionEvent e) {
* // if we're here then EDITOR != null
* Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
* }
* }
* </pre>
*/
@NonNull
public <T> T getRequiredData(Key<T> key) {
T data = getData(key);
assert data != null;
return data;
}
/**
* Returns the data context which allows to retrieve information about the state of the IDE
* related to the action invocation. (Active editor, fragment and so on)
*
* @return the data context instance
*/
public DataContext getDataContext() {
return mDataContext;
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public <T> void injectData(Key<T> key, T value) {
mDataContext.putData(key, value);
}
}
| 2,821 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ActionGroup.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/ActionGroup.java | package com.tyron.actions;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.beans.PropertyChangeSupport;
public abstract class ActionGroup extends AnAction {
private final PropertyChangeSupport mChangeSupport = new PropertyChangeSupport(this);
public static final ActionGroup EMPTY_GROUP =
new ActionGroup() {
@Override
public AnAction[] getChildren(@Nullable AnActionEvent e) {
return new AnAction[0];
}
};
@Override
public void actionPerformed(@NonNull AnActionEvent e) {}
public boolean isPopup() {
return true;
}
public abstract AnAction[] getChildren(@Nullable AnActionEvent e);
}
| 694 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
DataContext.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/DataContext.java | package com.tyron.actions;
import android.content.Context;
import android.content.ContextWrapper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.com.intellij.openapi.util.Key;
import org.jetbrains.kotlin.com.intellij.openapi.util.UserDataHolderBase;
public class DataContext extends ContextWrapper {
private final UserDataHolderBase mUserDataHolder;
public static DataContext wrap(Context context) {
if (context instanceof DataContext) {
return ((DataContext) context);
}
return new DataContext(context);
}
public DataContext(Context base) {
super(base);
mUserDataHolder = new UserDataHolderBase();
}
@Nullable
public <T> T getData(@NotNull Key<T> key) {
return mUserDataHolder.getUserData(key);
}
public <T> void putData(@NotNull Key<T> key, @Nullable T t) {
mUserDataHolder.putUserData(key, t);
}
}
| 929 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CommonDataKeys.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/CommonDataKeys.java | package com.tyron.actions;
import android.app.Activity;
import android.content.Context;
import androidx.fragment.app.Fragment;
import com.tyron.builder.model.DiagnosticWrapper;
import com.tyron.builder.project.Project;
import com.tyron.editor.Editor;
import com.tyron.fileeditor.api.FileEditor;
import java.io.File;
import org.jetbrains.kotlin.com.intellij.openapi.util.Key;
public class CommonDataKeys {
/** The current file opened in the editor */
public static final Key<File> FILE = Key.create("file");
public static final Key<Activity> ACTIVITY = Key.create("activity");
/** The current accessible context */
public static final Key<Context> CONTEXT = Key.create("context");
/** The current fragment this action is invoked on */
public static final Key<Fragment> FRAGMENT = Key.create("fragment");
public static final Key<DiagnosticWrapper> DIAGNOSTIC = Key.create("diagnostic");
/** The current opened project */
public static final Key<Project> PROJECT = Key.create("project");
public static final Key<Editor> EDITOR = Key.create("editor");
public static final Key<FileEditor> FILE_EDITOR_KEY = Key.create("fileEditor");
}
| 1,163 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ActionManager.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/ActionManager.java | package com.tyron.actions;
import android.view.Menu;
import androidx.annotation.NonNull;
import com.tyron.actions.impl.ActionManagerImpl;
public abstract class ActionManager {
private static ActionManager sInstance = null;
public static ActionManager getInstance() {
if (sInstance == null) {
sInstance = new ActionManagerImpl();
}
return sInstance;
}
public abstract void fillMenu(
DataContext context, Menu menu, String place, boolean isContext, boolean isToolbar);
public abstract String getId(@NonNull AnAction action);
public abstract void registerAction(@NonNull String actionId, @NonNull AnAction action);
public abstract void unregisterAction(@NonNull String actionId);
public abstract void replaceAction(@NonNull String actionId, @NonNull AnAction newAction);
public abstract boolean isGroup(@NonNull String actionId);
}
| 881 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
Presentation.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/Presentation.java | package com.tyron.actions;
import android.graphics.drawable.Drawable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.function.Supplier;
/** Controls how an action would look in the UI */
public class Presentation {
public static final Supplier<String> NULL_STRING = () -> null;
/** value: String */
public static final String PROP_DESCRIPTION = " description";
/** value: Drawable */
public static final String PROP_ICON = "icon";
/** value: Boolean */
public static final String PROP_VISIBLE = "visible";
/** value: Boolean */
public static final String PROP_ENABLED = "enabled";
private Drawable mIcon;
private boolean mIsVisible;
private boolean mIsEnabled = true;
private Supplier<String> mTextSupplier = NULL_STRING;
private Supplier<String> mDescriptionSupplier = NULL_STRING;
private PropertyChangeSupport mChangeSupport;
public Presentation() {}
public Presentation(Supplier<String> dynamicText) {
mTextSupplier = dynamicText;
}
public static Presentation createTemplatePresentation() {
return new Presentation();
}
public void addPropertyChangeListener(@NonNull PropertyChangeListener listener) {
PropertyChangeSupport support = mChangeSupport;
if (support == null) {
mChangeSupport = support = new PropertyChangeSupport(this);
}
support.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(@NonNull PropertyChangeListener listener) {
PropertyChangeSupport support = mChangeSupport;
if (support != null) {
mChangeSupport.removePropertyChangeListener(listener);
}
}
public String getText() {
return mTextSupplier.get();
}
public void setText(@Nullable String text) {
setText(() -> text);
}
public void setText(@NonNull Supplier<String> text) {
mTextSupplier = text;
}
public void setDescription(@NonNull Supplier<String> description) {
Supplier<String> oldDescription = mDescriptionSupplier;
mDescriptionSupplier = description;
fireObjectPropertyChange(PROP_DESCRIPTION, oldDescription, mDescriptionSupplier);
}
private void fireObjectPropertyChange(String propertyName, Object oldValue, Object newValue) {
// PropertyChangeSupport support = mChangeSupport;
// if (support != null && !Objects.equals(oldValue, newValue)) {
// support.firePropertyChange(propertyName, oldValue, newValue);
// }
}
private void fireBooleanPropertyChange(String propertyName, boolean oldValue, boolean newValue) {
// PropertyChangeSupport support = mChangeSupport;
// if (support != null && oldValue != newValue) {
// support.firePropertyChange(propertyName, oldValue, newValue);
// }
}
@NonNull
@Override
public Presentation clone() {
try {
return (Presentation) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public void setIcon(Drawable icon) {
mIcon = icon;
}
public Drawable getIcon() {
return mIcon;
}
public boolean isVisible() {
return mIsVisible;
}
public boolean isEnabled() {
return mIsEnabled;
}
public void setEnabled(boolean enabled) {
boolean old = mIsEnabled;
fireBooleanPropertyChange(PROP_ENABLED, old, enabled);
mIsEnabled = enabled;
}
public void setVisible(boolean visible) {
boolean old = mIsVisible;
fireBooleanPropertyChange(PROP_VISIBLE, old, visible);
mIsVisible = visible;
}
public String getDescription() {
return mDescriptionSupplier.get();
}
}
| 3,731 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ActionPlaces.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/ActionPlaces.java | package com.tyron.actions;
public class ActionPlaces {
/** The toolbar located in MainFragment */
public static final String MAIN_TOOLBAR = "main_toolbar";
/** Inside a CodeEditorFragment */
public static final String EDITOR = "editor";
/** The tab layout in an EditorContainerFragment */
public static final String EDITOR_TAB = "editorTab";
public static final String FILE_MANAGER = "fileManager";
}
| 420 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ActionManagerImpl.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/impl/ActionManagerImpl.java | package com.tyron.actions.impl;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Build;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import androidx.annotation.NonNull;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.tyron.actions.ActionGroup;
import com.tyron.actions.ActionManager;
import com.tyron.actions.AnAction;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.actions.DataContext;
import com.tyron.actions.Presentation;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class ActionManagerImpl extends ActionManager {
private final Map<String, AnAction> mIdToAction = new LinkedHashMap<>();
private final Map<Object, String> mActionToId = new HashMap<>();
@Override
public void fillMenu(
DataContext context, Menu menu, String place, boolean isContext, boolean isToolbar) {
// Inject values
context.putData(CommonDataKeys.CONTEXT, context);
if (Build.VERSION_CODES.P <= Build.VERSION.SDK_INT) {
menu.setGroupDividerEnabled(true);
}
for (AnAction value : mIdToAction.values()) {
AnActionEvent event =
new AnActionEvent(context, place, value.getTemplatePresentation(), isContext, isToolbar);
event.setPresentation(value.getTemplatePresentation());
value.update(event);
if (event.getPresentation().isVisible()) {
fillMenu(menu, value, event);
}
}
}
private void fillMenu(Menu menu, AnAction action, AnActionEvent event) {
Presentation presentation = event.getPresentation();
MenuItem menuItem;
if (isGroup(action)) {
ActionGroup actionGroup = (ActionGroup) action;
if (!actionGroup.isPopup()) {
fillMenu(View.generateViewId(), menu, actionGroup, event);
return;
}
SubMenu subMenu = menu.addSubMenu(presentation.getText());
menuItem = subMenu.getItem();
AnAction[] children = actionGroup.getChildren(event);
if (children != null) {
for (AnAction child : children) {
event.setPresentation(child.getTemplatePresentation());
child.update(event);
if (event.getPresentation().isVisible()) {
if (actionGroup.isPopup()) {
fillSubMenu(subMenu, child, event);
}
}
}
}
} else {
menuItem = menu.add(presentation.getText());
}
menuItem.setEnabled(presentation.isEnabled());
menuItem.setTitle(presentation.getText());
if (presentation.getIcon() != null) {
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
} else {
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
}
menuItem.setIcon(presentation.getIcon());
menuItem.setOnMenuItemClickListener(item -> performAction(action, event));
}
private void fillMenu(int id, Menu menu, ActionGroup group, AnActionEvent event) {
AnAction[] children = group.getChildren(event);
if (children == null) {
return;
}
for (AnAction child : children) {
event.setPresentation(child.getTemplatePresentation());
child.update(event);
if (event.getPresentation().isVisible()) {
MenuItem add = menu.add(id, Menu.NONE, Menu.NONE, event.getPresentation().getText());
add.setEnabled(event.getPresentation().isEnabled());
add.setIcon(event.getPresentation().getIcon());
add.setOnMenuItemClickListener(item -> performAction(child, event));
}
}
}
private void fillSubMenu(SubMenu subMenu, AnAction action, AnActionEvent event) {
Presentation presentation = event.getPresentation();
MenuItem menuItem;
if (isGroup(action)) {
ActionGroup group = (ActionGroup) action;
if (!group.isPopup()) {
fillMenu(View.generateViewId(), subMenu, group, event);
}
SubMenu subSubMenu = subMenu.addSubMenu(presentation.getText());
menuItem = subSubMenu.getItem();
AnAction[] children = group.getChildren(event);
if (children != null) {
for (AnAction child : children) {
event.setPresentation(child.getTemplatePresentation());
child.update(event);
if (event.getPresentation().isVisible()) {
fillSubMenu(subSubMenu, child, event);
}
}
}
} else {
menuItem = subMenu.add(presentation.getText());
}
menuItem.setEnabled(presentation.isEnabled());
if (presentation.getIcon() != null) {
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
} else {
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
}
menuItem.setIcon(presentation.getIcon());
menuItem.setContentDescription(presentation.getDescription());
menuItem.setOnMenuItemClickListener(item -> performAction(action, event));
}
private boolean performAction(AnAction action, AnActionEvent event) {
try {
action.actionPerformed(event);
} catch (Throwable e) {
ClipboardManager clipboardManager =
event.getDataContext().getSystemService(ClipboardManager.class);
new MaterialAlertDialogBuilder(event.getDataContext())
.setTitle("Unable to perform action")
.setMessage(e.getMessage())
.setPositiveButton(android.R.string.ok, null)
.setNegativeButton(
android.R.string.copy,
(d, w) ->
clipboardManager.setPrimaryClip(
ClipData.newPlainText("Error report", Log.getStackTraceString(e))))
.show();
return false;
}
return true;
}
@Override
public String getId(@NonNull AnAction action) {
return mActionToId.get(action);
}
@Override
public void registerAction(@NonNull String actionId, @NonNull AnAction action) {
mIdToAction.put(actionId, action);
mActionToId.put(action, actionId);
}
@Override
public void unregisterAction(@NonNull String actionId) {
AnAction anAction = mIdToAction.get(actionId);
if (anAction != null) {
mIdToAction.remove(actionId);
mActionToId.remove(anAction);
}
}
@Override
public void replaceAction(@NonNull String actionId, @NonNull AnAction newAction) {
unregisterAction(actionId);
registerAction(actionId, newAction);
}
@Override
public boolean isGroup(@NonNull String actionId) {
return isGroup(mIdToAction.get(actionId));
}
private boolean isGroup(AnAction action) {
return action instanceof ActionGroup;
}
}
| 6,643 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
PresentationFactory.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/impl/PresentationFactory.java | package com.tyron.actions.impl;
import androidx.annotation.NonNull;
import com.tyron.actions.AnAction;
import com.tyron.actions.Presentation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.WeakHashMap;
public class PresentationFactory {
private final Map<AnAction, Presentation> mPresentations = new WeakHashMap<>();
private boolean mNeedRebuild;
private static final Collection<PresentationFactory> sAllFactories = new ArrayList<>();
public PresentationFactory() {
sAllFactories.add(this);
}
public final Presentation getPresentation(@NonNull AnAction action) {
Presentation presentation = mPresentations.get(action);
if (presentation == null) {
Presentation templatePresentation = action.getTemplatePresentation();
presentation = templatePresentation.clone();
presentation = mPresentations.putIfAbsent(action, presentation);
processPresentation(Objects.requireNonNull(presentation));
}
return presentation;
}
protected void processPresentation(@NonNull Presentation presentation) {}
public void reset() {
mPresentations.clear();
}
public static void clearPresentationCaches() {
for (PresentationFactory factory : sAllFactories) {
factory.reset();
}
}
}
| 1,326 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ActionToolbar.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/impl/ActionToolbar.java | package com.tyron.actions.impl;
import android.content.Context;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import com.tyron.actions.DataContext;
/** A toolbar that holds a {@link DataContext} */
public class ActionToolbar extends Toolbar {
public ActionToolbar(@NonNull Context context) {
this(DataContext.wrap(context), null);
}
public ActionToolbar(@NonNull Context context, @Nullable AttributeSet attrs) {
super(DataContext.wrap(context), attrs);
}
public ActionToolbar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(DataContext.wrap(context), attrs, defStyleAttr);
}
}
| 743 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
DataContextUtils.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/actions-api/src/main/java/com/tyron/actions/util/DataContextUtils.java | package com.tyron.actions.util;
import android.content.Context;
import android.view.View;
import com.tyron.actions.DataContext;
public class DataContextUtils {
public static DataContext getDataContext(View view) {
Context context = view.getContext();
if (context instanceof DataContext) {
return (DataContext) context;
}
return new DataContext(context);
}
}
| 388 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FindNewTypeDeclarationAt.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/FindNewTypeDeclarationAt.java | package com.tyron.completion.java;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;
public class FindNewTypeDeclarationAt extends TreeScanner<ClassTree, Long> {
private final SourcePositions pos;
private final CompilationUnitTree root;
public FindNewTypeDeclarationAt(JavacTask task, CompilationUnitTree root) {
this.pos = Trees.instance(task).getSourcePositions();
this.root = root;
}
@Override
public ClassTree visitNewClass(NewClassTree t, Long find) {
if (pos == null) {
return null;
}
ClassTree smaller = super.visitNewClass(t, find);
if (smaller != null) {
return smaller;
}
if (pos.getStartPosition(root, t.getClassBody()) <= find
&& find < pos.getEndPosition(root, t.getClassBody())) {
return t.getClassBody();
}
return null;
}
@Override
public ClassTree reduce(ClassTree a, ClassTree b) {
if (a != null) return a;
return b;
}
}
| 1,175 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FindTypeDeclarations.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/FindTypeDeclarations.java | package com.tyron.completion.java;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.TreeScanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class FindTypeDeclarations extends TreeScanner<Void, List<String>> {
private final List<CharSequence> qualifiedName = new ArrayList<>();
@Override
public Void visitCompilationUnit(CompilationUnitTree root, List<String> found) {
String name = Objects.toString(root.getPackageName(), "");
qualifiedName.add(name);
return super.visitCompilationUnit(root, found);
}
@Override
public Void visitClass(ClassTree type, List<String> found) {
qualifiedName.add(type.getSimpleName());
found.add(String.join(".", qualifiedName));
super.visitClass(type, found);
qualifiedName.remove(qualifiedName.size() - 1);
return null;
}
}
| 909 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CustomActions.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/CustomActions.java | package com.tyron.completion.java;
import com.tyron.completion.java.compiler.ParseTask;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.CompletionList;
import java.util.ArrayList;
import java.util.List;
/** Convenience class for getting completions on custom actions like Overriding a method */
public class CustomActions {
private static final String TAG = CustomActions.class.getSimpleName();
public static List<CompletionItem> addCustomActions(ParseTask task, String partial) {
List<CompletionItem> items = new ArrayList<>();
return items;
}
public static void addOverrideItem(CompletionList list) {
CompletionItem item = new CompletionItem();
item.action = CompletionItem.Kind.OVERRIDE;
item.label = "Override methods";
item.commitText = "";
item.cursorOffset = 0;
item.detail = "";
list.items.add(0, item);
}
}
| 904 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FindTypeDeclarationAt.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/FindTypeDeclarationAt.java | package com.tyron.completion.java;
import android.util.Pair;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ErroneousTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;
import java.util.List;
public class FindTypeDeclarationAt extends TreeScanner<ClassTree, Long> {
private final SourcePositions pos;
private final JavacTask task;
private CompilationUnitTree root;
public FindTypeDeclarationAt(JavacTask task) {
this.task = task;
pos = Trees.instance(task).getSourcePositions();
}
@Override
public ClassTree visitCompilationUnit(CompilationUnitTree t, Long find) {
root = t;
return super.visitCompilationUnit(t, find);
}
@Override
public ClassTree visitClass(ClassTree t, Long find) {
ClassTree smaller = super.visitClass(t, find);
if (smaller != null) {
return smaller;
}
if (isInside(t, Pair.create(find, find))) {
return t;
}
return null;
}
@Override
public ClassTree visitErroneous(ErroneousTree tree, Long find) {
final List<? extends Tree> errorTrees = tree.getErrorTrees();
if (errorTrees != null) {
for (Tree errorTree : errorTrees) {
final ClassTree scan = scan(errorTree, find);
if (scan != null) {
return scan;
}
}
}
return null;
}
@Override
public ClassTree reduce(ClassTree a, ClassTree b) {
if (a != null) return a;
return b;
}
private boolean isInside(Tree tree, Pair<Long, Long> find) {
long start = pos.getStartPosition(root, tree);
long end = pos.getEndPosition(root, tree);
return start <= find.first && find.second <= end;
}
}
| 1,836 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaCompilerProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/JavaCompilerProvider.java | package com.tyron.completion.java;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.AndroidModule;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.builder.project.api.Module;
import com.tyron.completion.index.CompilerProvider;
import com.tyron.completion.index.CompilerService;
import com.tyron.completion.java.compiler.JavaCompilerService;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class JavaCompilerProvider extends CompilerProvider<JavaCompilerService> {
public static final String KEY = JavaCompilerProvider.class.getSimpleName();
@Nullable
public static JavaCompilerService get(@NonNull Project project, @NonNull JavaModule module) {
Object index = CompilerService.getInstance().getIndex(KEY);
if (!(index instanceof JavaCompilerProvider)) {
return null;
}
JavaCompilerProvider provider = ((JavaCompilerProvider) index);
return provider.getCompiler(project, module);
}
private volatile JavaCompilerService mProvider;
private final Set<File> mCachedPaths;
public JavaCompilerProvider() {
mCachedPaths = new HashSet<>();
}
@Override
public synchronized JavaCompilerService get(Project project, Module module) {
if (module instanceof JavaModule) {
return getCompiler(project, (JavaModule) module);
}
return null;
}
public void destroy() {
mCachedPaths.clear();
mProvider = null;
}
public synchronized JavaCompilerService getCompiler(Project project, JavaModule module) {
List<Module> dependencies = new ArrayList<>();
if (project != null) {
dependencies.addAll(project.getDependencies(module));
}
Set<File> paths = new HashSet<>();
for (Module dependency : dependencies) {
if (dependency instanceof JavaModule) {
paths.addAll(((JavaModule) dependency).getJavaFiles().values());
paths.addAll(((JavaModule) dependency).getLibraries());
paths.addAll(((JavaModule) dependency).getInjectedClasses().values());
}
if (dependency instanceof AndroidModule) {
File buildGenDir = new File(dependency.getRootFile() + "/build/gen");
File viewBindingDir = new File(dependency.getRootFile() + "/build/view_binding");
paths.add(
new File(
dependency.getRootFile(),
"/build/libraries/kotlin_runtime/" + dependency.getRootFile().getName() + ".jar"));
if (buildGenDir.exists()) {
paths.addAll(getFiles(buildGenDir, ".java"));
}
if (viewBindingDir.exists()) {
paths.addAll(getFiles(viewBindingDir, ".java"));
}
}
}
if (mProvider == null || changed(mCachedPaths, paths)) {
mProvider =
new JavaCompilerService(project, paths, Collections.emptySet(), Collections.emptySet());
mCachedPaths.clear();
mCachedPaths.addAll(paths);
mProvider.setCurrentModule(module);
}
return mProvider;
}
private synchronized boolean changed(Set<File> oldFiles, Set<File> newFiles) {
if (oldFiles.size() != newFiles.size()) {
return true;
}
for (File oldFile : oldFiles) {
if (!newFiles.contains(oldFile)) {
return true;
}
}
for (File newFile : newFiles) {
if (!oldFiles.contains(newFile)) {
return true;
}
}
return false;
}
public Set<File> getFiles(File dir, String ext) {
Set<File> Files = new HashSet<>();
File[] files = dir.listFiles();
if (files == null) {
return Collections.emptySet();
}
for (File file : files) {
if (file.isDirectory()) {
Files.addAll(getFiles(file, ext));
} else {
if (file.getName().endsWith(ext)) {
Files.add(file);
}
}
}
return Files;
}
public static File getOrCreateResourceClass(JavaModule module) throws IOException {
File outputDirectory = new File(module.getBuildDirectory(), "injected/resource");
if (!outputDirectory.exists() && !outputDirectory.mkdirs()) {
throw new IOException("Unable to create directory " + outputDirectory);
}
File classFile = new File(outputDirectory, "R.java");
if (!classFile.exists() && !classFile.createNewFile()) {
throw new IOException("Unable to create " + classFile);
}
return classFile;
}
public void clear() {
mProvider = null;
}
}
| 4,631 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompletionModule.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/CompletionModule.java | package com.tyron.completion.java;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import androidx.annotation.VisibleForTesting;
import com.tyron.actions.ActionManager;
import com.tyron.builder.BuildModule;
import com.tyron.common.util.Decompress;
import com.tyron.completion.java.action.context.IntroduceLocalVariableAction;
import com.tyron.completion.java.action.context.OverrideInheritedMethodsAction;
import com.tyron.completion.java.action.quickfix.AddCatchClauseAction;
import com.tyron.completion.java.action.quickfix.AddThrowsAction;
import com.tyron.completion.java.action.quickfix.ImplementAbstractMethodsFix;
import com.tyron.completion.java.action.quickfix.ImportClassAction;
import com.tyron.completion.java.action.quickfix.ImportClassFieldFix;
import com.tyron.completion.java.action.quickfix.SurroundWithTryCatchAction;
import java.io.File;
public class CompletionModule {
private static Context sApplicationContext;
private static final Handler sApplicationHandler = new Handler(Looper.getMainLooper());
private static File sAndroidJar;
private static File sLambdaStubs;
public static void registerActions(ActionManager actionManager) {
actionManager.registerAction(AddThrowsAction.ID, new AddThrowsAction());
actionManager.registerAction(AddCatchClauseAction.ID, new AddCatchClauseAction());
actionManager.registerAction(SurroundWithTryCatchAction.ID, new SurroundWithTryCatchAction());
actionManager.registerAction(ImportClassAction.ID, new ImportClassAction());
actionManager.registerAction(ImportClassFieldFix.ID, new ImportClassFieldFix());
actionManager.registerAction(ImplementAbstractMethodsFix.ID, new ImplementAbstractMethodsFix());
actionManager.registerAction(
IntroduceLocalVariableAction.ID, new IntroduceLocalVariableAction());
actionManager.registerAction(
OverrideInheritedMethodsAction.ID, new OverrideInheritedMethodsAction());
}
public static void initialize(Context context) {
sApplicationContext = context.getApplicationContext();
}
public static Context getContext() {
return sApplicationContext;
}
public static void post(Runnable runnable) {
sApplicationHandler.post(runnable);
}
public static File getAndroidJar() {
if (sAndroidJar == null) {
Context context = BuildModule.getContext();
if (context == null) {
return null;
}
sAndroidJar = new File(context.getFilesDir(), "rt.jar");
if (!sAndroidJar.exists()) {
Decompress.unzipFromAssets(
BuildModule.getContext(), "rt.zip", sAndroidJar.getParentFile().getAbsolutePath());
}
}
return sAndroidJar;
}
public static File getLambdaStubs() {
if (sLambdaStubs == null) {
sLambdaStubs = new File(BuildModule.getContext().getFilesDir(), "core-lambda-stubs.jar");
if (!sLambdaStubs.exists()) {
Decompress.unzipFromAssets(
BuildModule.getContext(),
"lambda-stubs.zip",
sLambdaStubs.getParentFile().getAbsolutePath());
}
}
return sLambdaStubs;
}
@VisibleForTesting
public static void setLambdaStubs(File file) {
sLambdaStubs = file;
}
@VisibleForTesting
public static void setAndroidJar(File file) {
sAndroidJar = file;
}
public static SharedPreferences getPreferences() {
return PreferenceManager.getDefaultSharedPreferences(sApplicationContext);
}
}
| 3,544 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompilerProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/CompilerProvider.java | package com.tyron.completion.java;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.compiler.ParseTask;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.tools.JavaFileObject;
public interface CompilerProvider {
Set<String> imports();
Set<String> publicTopLevelTypes();
List<String> packagePrivateTopLevelTypes(String packageName);
Iterable<Path> search(String query);
Optional<JavaFileObject> findAnywhere(String className);
Path findTypeDeclaration(String className);
Path[] findTypeReferences(String className);
Path[] findMemberReferences(String className, String memberName);
ParseTask parse(Path file);
ParseTask parse(JavaFileObject file);
CompilerContainer compile(Path... files);
CompilerContainer compile(Collection<? extends JavaFileObject> sources);
Path NOT_FOUND = Paths.get("");
}
| 1,001 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/JavaCompletionProvider.java | package com.tyron.completion.java;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import android.util.Log;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.builder.project.api.KotlinModule;
import com.tyron.completion.CompletionParameters;
import com.tyron.completion.CompletionProvider;
import com.tyron.completion.index.CompilerService;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.provider.Completions;
import com.tyron.completion.java.provider.JavaKotlincCompletionProvider;
import com.tyron.completion.model.CachedCompletion;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.CompletionList;
import com.tyron.completion.progress.ProcessCanceledException;
import com.tyron.completion.progress.ProgressManager;
import com.tyron.kotlin.completion.core.model.KotlinEnvironment;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import me.xdrop.fuzzywuzzy.FuzzySearch;
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment;
import org.jetbrains.kotlin.com.intellij.openapi.editor.Document;
import org.jetbrains.kotlin.com.intellij.openapi.editor.impl.event.DocumentEventImpl;
import org.jetbrains.kotlin.com.intellij.openapi.progress.ProgressIndicator;
import org.jetbrains.kotlin.com.intellij.openapi.progress.impl.CoreProgressManager;
import org.jetbrains.kotlin.com.intellij.openapi.progress.util.AbstractProgressIndicatorBase;
import org.jetbrains.kotlin.com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.kotlin.com.intellij.psi.PsiDocumentManager;
import org.jetbrains.kotlin.com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiFile;
import org.jetbrains.kotlin.com.intellij.psi.PsiFileFactory;
import org.jetbrains.kotlin.com.intellij.psi.PsiManager;
import org.jetbrains.kotlin.com.intellij.psi.impl.PsiDocumentManagerBase;
public class JavaCompletionProvider extends CompletionProvider {
private static final String COMPLETION_THREAD_CLASS =
"io.github.rosemoe.sora.widget.component.EditorAutoCompletion$CompletionThread";
private static final Field sCanceledField;
static {
try {
Class<?> completionThreadClass = Class.forName(COMPLETION_THREAD_CLASS);
sCanceledField = completionThreadClass.getDeclaredField("mAborted");
sCanceledField.setAccessible(true);
} catch (Throwable e) {
throw new Error("Rosemoe thread implementation has changed", e);
}
}
private CachedCompletion mCachedCompletion;
public JavaCompletionProvider() {}
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().endsWith(".java");
}
@Override
public CompletionList complete(CompletionParameters params) {
if (!(params.getModule() instanceof JavaModule)) {
return CompletionList.EMPTY;
}
checkCanceled();
if (isIncrementalCompletion(mCachedCompletion, params)) {
String partial = partialIdentifier(params.getPrefix(), params.getPrefix().length());
CompletionList cachedList = mCachedCompletion.getCompletionList();
CompletionList copy = CompletionList.copy(cachedList, partial);
// if the cached completion is incomplete,
// chances are there will be new items that are not in the cache
// so don't return the cached items
if (!copy.isIncomplete && !copy.items.isEmpty()) {
return copy;
}
}
CompletionList.Builder complete =
complete(
params.getProject(),
(JavaModule) params.getModule(),
params.getFile(),
params.getContents(),
params.getIndex());
if (complete == null) {
return CompletionList.EMPTY;
}
CompletionList list = complete.build();
String newPrefix = params.getPrefix();
if (params.getPrefix().contains(".")) {
newPrefix = partialIdentifier(params.getPrefix(), params.getPrefix().length());
}
mCachedCompletion =
new CachedCompletion(
params.getFile(), params.getLine(), params.getColumn(), newPrefix, list);
return list;
}
public CompletionList.Builder completeWithKotlinc(
Project project, JavaModule module, File file, String contents, long cursor) {
if (!(module instanceof KotlinModule)) {
// should not happen as all android modules are kotlin module
throw new RuntimeException("Not a kotlin module");
}
KotlinModule kotlinModule = ((KotlinModule) module);
KotlinCoreEnvironment environment = KotlinEnvironment.getEnvironment(kotlinModule);
org.jetbrains.kotlin.com.intellij.openapi.project.Project jetProject = environment.getProject();
setCurrentIndicator();
VirtualFile virtualFile =
environment
.getProjectEnvironment()
.getEnvironment()
.getLocalFileSystem()
.findFileByIoFile(file);
assert virtualFile != null && virtualFile.isValid();
PsiFile storedPsi = PsiManager.getInstance(jetProject).findFile(virtualFile);
assert storedPsi != null && storedPsi.isValid();
String oldText = storedPsi.getText();
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(jetProject);
Document document = documentManager.getDocument(storedPsi);
assert document != null;
document.setText(contents);
DocumentEventImpl event =
new DocumentEventImpl(
document, 0, oldText, contents, storedPsi.getModificationStamp(), true);
((PsiDocumentManagerBase) documentManager).documentChanged(event);
PsiFileFactory factory = PsiFileFactory.getInstance(jetProject);
PsiFile parsed = factory.createFileFromText(contents, storedPsi);
assert parsed != null;
storedPsi.getViewProvider().rootChanged(parsed);
PsiElement elementAt = parsed.findElementAt((int) (cursor - 1));
assert elementAt != null;
CompletionList.Builder builder = new CompletionList.Builder(elementAt.getText());
JavaKotlincCompletionProvider provider = new JavaKotlincCompletionProvider(module);
provider.fillCompletionVariants(elementAt, builder);
return builder;
}
private void setCurrentIndicator() {
try {
ProgressIndicator indicator =
new AbstractProgressIndicatorBase() {
@Override
public void checkCanceled() {
ProgressManager.checkCanceled();
if (Thread.currentThread().getClass().getName().equals(COMPLETION_THREAD_CLASS)) {
try {
Object o = sCanceledField.get(Thread.currentThread());
if (o instanceof Boolean) {
if (((Boolean) o)) {
cancel();
}
}
} catch (IllegalAccessException e) {
// ignored
}
}
super.checkCanceled();
}
};
// the kotlin compiler does not provide implementations to run a progress indicator,
// since the PSI infrastructure calls ProgressManager#checkCancelled, we need this
// hack to make thread cancellation work
Method setCurrentIndicator =
CoreProgressManager.class.getDeclaredMethod(
"setCurrentIndicator", long.class, ProgressIndicator.class);
setCurrentIndicator.setAccessible(true);
setCurrentIndicator.invoke(null, Thread.currentThread().getId(), indicator);
} catch (Throwable e) {
throw new Error(e);
}
}
public CompletionList.Builder complete(
Project project, JavaModule module, File file, String contents, long cursor) {
JavaCompilerProvider compilerProvider =
CompilerService.getInstance().getIndex(JavaCompilerProvider.KEY);
JavaCompilerService service = compilerProvider.getCompiler(project, module);
try {
return new Completions(service).complete(file, contents, cursor);
} catch (Throwable e) {
if (e instanceof ProcessCanceledException) {
throw e;
}
if (BuildConfig.DEBUG) {
Log.e("JavaCompletionProvider", "Unable to get completions", e);
}
service.destroy();
}
return null;
}
private String partialIdentifier(String contents, int end) {
int start = end;
while (start > 0 && Character.isJavaIdentifierPart(contents.charAt(start - 1))) {
start--;
}
return contents.substring(start, end);
}
private int getRatio(CompletionItem item, String partialIdentifier) {
String label = getLabel(item);
return FuzzySearch.ratio(label, partialIdentifier);
}
private String getLabel(CompletionItem item) {
String label = item.label;
if (label.contains("(")) {
label = label.substring(0, label.indexOf('('));
}
return label;
}
private boolean isIncrementalCompletion(
CachedCompletion cachedCompletion, CompletionParameters params) {
String prefix = params.getPrefix();
File file = params.getFile();
int line = params.getLine();
int column = params.getColumn();
prefix = partialIdentifier(prefix, prefix.length());
if (line == -1) {
return false;
}
if (column == -1) {
return false;
}
if (cachedCompletion == null) {
return false;
}
if (!file.equals(cachedCompletion.getFile())) {
return false;
}
if (prefix.endsWith(".")) {
return false;
}
if (cachedCompletion.getLine() != line) {
return false;
}
if (cachedCompletion.getColumn() > column) {
return false;
}
if (!prefix.startsWith(cachedCompletion.getPrefix())) {
return false;
}
return prefix.length() - cachedCompletion.getPrefix().length()
== column - cachedCompletion.getColumn();
}
}
| 9,846 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
Docs.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/Docs.java | package com.tyron.completion.java;
import android.content.Context;
import com.tyron.builder.project.Project;
import com.tyron.common.util.Decompress;
import com.tyron.completion.java.compiler.SourceFileManager;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.tools.StandardLocation;
/** Main class that holds all the files that ends with "-sources" including android.jar sources */
public class Docs {
public final SourceFileManager fileManager;
public Docs(Project project, Set<File> docPaths) {
// we include android sources into the list
fileManager = new SourceFileManager(project);
File srcZip = androidSourcesZip();
List<File> sourcePaths = new ArrayList<>(docPaths);
if (srcZip != NOT_FOUND) {
sourcePaths.add(srcZip);
}
try {
fileManager.setLocation(StandardLocation.SOURCE_PATH, sourcePaths);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static final File NOT_FOUND = new File("");
private static File cacheAndroidSources;
private static File androidSourcesZip() {
if (cacheAndroidSources == null) {
try {
cacheAndroidSources = findAndroidSources();
} catch (IOException e) {
cacheAndroidSources = NOT_FOUND;
}
}
if (cacheAndroidSources == NOT_FOUND) {
return NOT_FOUND;
}
return cacheAndroidSources;
}
private static final File EMPTY = new File("");
// TODO: im gonna bundle the java docs sources in the app assets for now
// we could let the user download it later.
private static File findAndroidSources() throws IOException {
Context context = CompletionModule.getContext();
if (context == null) {
return EMPTY;
}
File sourcePath =
new File(CompletionModule.getContext().getFilesDir(), "docs/android-sources.jar");
if (!sourcePath.exists()) {
if (!sourcePath.getParentFile().mkdirs()) {
throw new IOException("Couldn't create directory for android sources");
}
Decompress.unzipFromAssets(
CompletionModule.getContext(), "android-sources.zip", sourcePath.getParent());
}
return sourcePath;
}
}
| 2,245 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CircleDrawable.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/drawable/CircleDrawable.java | package com.tyron.completion.java.drawable;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import com.tyron.completion.java.CompletionModule;
import com.tyron.completion.model.DrawableKind;
public class CircleDrawable extends Drawable {
private final Paint mPaint;
private final Paint mTextPaint;
private final DrawableKind mKind;
private final boolean mCircle;
public CircleDrawable(DrawableKind kind) {
this(kind, false);
}
public CircleDrawable(DrawableKind kind, boolean circle) {
mKind = kind;
mCircle = circle;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(kind.getColor());
mTextPaint = new Paint();
mTextPaint.setColor(0xffffffff);
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(dp(14));
mTextPaint.setTextAlign(Paint.Align.CENTER);
}
@Override
public void draw(Canvas canvas) {
float width = getBounds().right;
float height = getBounds().bottom;
if (mCircle) {
canvas.drawCircle(width / 2, height / 2, width / 2, mPaint);
} else {
canvas.drawRect(0, 0, width, height, mPaint);
}
canvas.save();
canvas.translate(width / 2f, height / 2f);
float textCenter = (-(mTextPaint.descent() + mTextPaint.ascent()) / 2f);
canvas.drawText(mKind.getValue(), 0, textCenter, mTextPaint);
canvas.restore();
}
@Override
public void setAlpha(int p1) {
throw new UnsupportedOperationException("setAlpha is not supported on CircleDrawable");
}
@Override
public void setColorFilter(ColorFilter p1) {}
@Override
public int getOpacity() {
return PixelFormat.OPAQUE;
}
private static float dp(int px) {
return Math.round(
CompletionModule.getContext().getResources().getDisplayMetrics().density * px);
}
}
| 1,922 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
IntroduceLocalVariable.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/IntroduceLocalVariable.java | package com.tyron.completion.java.rewrite;
import static com.tyron.completion.java.util.ActionUtil.containsVariableAtScope;
import static com.tyron.completion.java.util.ActionUtil.getVariableName;
import com.google.common.collect.ImmutableMap;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.java.util.ElementUtil;
import com.tyron.completion.java.util.PrintHelper;
import com.tyron.completion.model.Range;
import com.tyron.completion.model.TextEdit;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.lang.model.type.TypeMirror;
public class IntroduceLocalVariable implements JavaRewrite {
private final Path file;
private final String methodName;
private final TypeMirror type;
private final long position;
public IntroduceLocalVariable(Path file, String methodName, TypeMirror type, long position) {
this.file = file;
this.methodName = methodName;
this.type = type;
this.position = position;
}
@Override
public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
CompilerContainer container = compiler.compile(file);
return container.get(
task -> {
List<TextEdit> edits = new ArrayList<>();
Range range = new Range(position, position);
String variableType = PrintHelper.printType(type, false);
String variableName = ActionUtil.guessNameFromMethodName(methodName);
if (variableName == null) {
variableName = ActionUtil.guessNameFromType(type);
}
if (variableName == null) {
variableName = "variable";
}
while (containsVariableAtScope(variableName, position, task)) {
variableName = getVariableName(variableName);
}
TextEdit edit = new TextEdit(range, variableType + " " + variableName + " = ");
edits.add(edit);
if (!type.getKind().isPrimitive()) {
List<String> classes = ElementUtil.getAllClasses(type);
for (String aClass : classes) {
if (!ActionUtil.hasImport(task.root(), aClass)) {
AddImport addImport = new AddImport(file.toFile(), aClass);
Map<Path, TextEdit[]> rewrite = addImport.rewrite(compiler);
TextEdit[] imports = rewrite.get(file);
if (imports != null) {
Collections.addAll(edits, imports);
}
}
}
}
return ImmutableMap.of(file, edits.toArray(new TextEdit[0]));
});
}
}
| 2,742 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
EditHelper.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/EditHelper.java | package com.tyron.completion.java.rewrite;
import static com.tyron.completion.java.patterns.JavacTreePatterns.classTree;
import static com.tyron.completion.java.patterns.JavacTreePatterns.method;
import static com.tyron.completion.java.patterns.JavacTreePatterns.tree;
import androidx.annotation.NonNull;
import com.github.javaparser.ast.Modifier.Keyword;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.BooleanLiteralExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.IntegerLiteralExpr;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.NullLiteralExpr;
import com.github.javaparser.ast.expr.SuperExpr;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ReturnStmt;
import com.github.javaparser.ast.type.PrimitiveType;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.LineMap;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.code.Symbol;
import com.tyron.completion.java.patterns.ClassTreePattern;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.java.util.JavaParserTypesUtil;
import com.tyron.completion.java.util.JavaParserUtil;
import com.tyron.completion.java.util.TreeUtil;
import com.tyron.completion.model.Position;
import com.tyron.completion.model.Range;
import com.tyron.completion.model.TextEdit;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public class EditHelper {
final JavacTask task;
public EditHelper(JavacTask task) {
this.task = task;
}
public TextEdit removeTree(CompilationUnitTree root, Tree remove) {
SourcePositions pos = Trees.instance(task).getSourcePositions();
LineMap lines = root.getLineMap();
long start = pos.getStartPosition(root, remove);
long end = pos.getEndPosition(root, remove);
int startLine = (int) lines.getLineNumber(start);
int startColumn = (int) lines.getColumnNumber(start);
Position startPos = new Position(startLine - 1, startColumn - 1);
int endLine = (int) lines.getLineNumber(end);
int endColumn = (int) lines.getColumnNumber(end);
Position endPos = new Position(endLine - 1, endColumn - 1);
Range range = new Range(startPos, endPos);
return new TextEdit(range, "");
}
/**
* Prints a given method into a String, adds {@code throws UnsupportedOperationException} to the
* method body if the source is null, it will get the parameter names from the class file which
* will be {@code arg1, arg2, arg3}
*
* @param method method to print
* @param parameterizedType type parameters of this method
* @param source the source method, in which the parameter names are fetched
* @return a string that represents the method
*/
public static MethodDeclaration printMethod(
ExecutableElement method, ExecutableType parameterizedType, MethodTree source) {
MethodDeclaration methodDeclaration =
JavaParserUtil.toMethodDeclaration(source, parameterizedType);
printMethodInternal(methodDeclaration, method);
return methodDeclaration;
}
public static MethodDeclaration printMethod(
ExecutableElement method, ExecutableType parameterizedType, ExecutableElement source) {
MethodDeclaration methodDeclaration =
JavaParserUtil.toMethodDeclaration(method, parameterizedType);
printMethodInternal(methodDeclaration, source);
return methodDeclaration;
}
private static void printMethodInternal(
MethodDeclaration methodDeclaration, ExecutableElement method) {
methodDeclaration.addMarkerAnnotation(Override.class);
Optional<AnnotationExpr> recentlyNonNull =
methodDeclaration.getAnnotationByName("RecentlyNonNull");
if (recentlyNonNull.isPresent()) {
methodDeclaration.remove(recentlyNonNull.get());
methodDeclaration.addMarkerAnnotation(NonNull.class);
}
BlockStmt blockStmt = new BlockStmt();
if (method.getModifiers().contains(Modifier.ABSTRACT)) {
methodDeclaration.removeModifier(Keyword.ABSTRACT);
if (methodDeclaration.getType().isClassOrInterfaceType()) {
blockStmt.addStatement(new ReturnStmt(new NullLiteralExpr()));
}
if (methodDeclaration.getType().isPrimitiveType()) {
PrimitiveType type = methodDeclaration.getType().asPrimitiveType();
blockStmt.addStatement(new ReturnStmt(getReturnExpr(type)));
}
} else {
MethodCallExpr methodCallExpr = new MethodCallExpr();
methodCallExpr.setName(methodDeclaration.getName());
methodCallExpr.setArguments(
methodDeclaration.getParameters().stream()
.map(NodeWithSimpleName::getNameAsExpression)
.collect(NodeList.toNodeList()));
methodCallExpr.setScope(new SuperExpr());
if (methodDeclaration.getType().isVoidType()) {
blockStmt.addStatement(methodCallExpr);
} else {
blockStmt.addStatement(new ReturnStmt(methodCallExpr));
}
}
methodDeclaration.setBody(blockStmt);
}
private static Expression getReturnExpr(PrimitiveType type) {
switch (type.getType()) {
case BOOLEAN:
return new BooleanLiteralExpr();
case BYTE:
case DOUBLE:
case CHAR:
case SHORT:
case LONG:
case FLOAT:
case INT:
return new IntegerLiteralExpr("0");
default:
return new NullLiteralExpr();
}
}
public static String printThrows(@NonNull List<? extends TypeMirror> thrownTypes) {
StringBuilder types = new StringBuilder();
for (TypeMirror m : thrownTypes) {
types.append((types.length() == 0) ? "" : ", ").append(printType(m));
}
return "throws " + types;
}
public static String printBody(ExecutableElement method, MethodTree source) {
TypeMirror returnType = method.getReturnType();
if (!method.getModifiers().contains(Modifier.ABSTRACT)) {
String body;
if (method.getParameters().size() == 0) {
body = "super." + method.getSimpleName() + "();";
} else {
String names;
if (source != null) {
names =
source.getParameters().stream()
.map(VariableTree::getName)
.map(Name::toString)
.collect(Collectors.joining(", "));
} else {
names =
method.getParameters().stream()
.map(VariableElement::getSimpleName)
.map(Name::toString)
.collect(Collectors.joining(", "));
}
body = "super." + method.getSimpleName() + "(" + names + ");";
}
return returnType.getKind() == TypeKind.VOID ? body : "return " + body;
}
switch (returnType.getKind()) {
case VOID:
return "";
case SHORT:
case CHAR:
case FLOAT:
case BYTE:
case INT:
return "return 0;";
case BOOLEAN:
return "return false;";
default:
return "return null;";
}
}
public static String printBody(ExecutableElement method, ExecutableElement source) {
TypeMirror returnType = method.getReturnType();
if (!method.getModifiers().contains(Modifier.ABSTRACT)) {
String body;
if (method.getParameters().size() == 0) {
body = "super." + method.getSimpleName() + "();";
} else {
String names;
if (source != null) {
names =
source.getParameters().stream()
.map(VariableElement::getSimpleName)
.map(Name::toString)
.collect(Collectors.joining(", "));
} else {
names =
method.getParameters().stream()
.map(VariableElement::getSimpleName)
.map(Name::toString)
.collect(Collectors.joining(", "));
}
body = "super." + method.getSimpleName() + "(" + names + ");";
}
return returnType.getKind() == TypeKind.VOID ? body : "return " + body;
}
switch (returnType.getKind()) {
case VOID:
return "";
case SHORT:
case CHAR:
case FLOAT:
case BYTE:
case INT:
return "return 0;";
case BOOLEAN:
return "return false;";
default:
return "return null;";
}
}
/**
* Prints parameters given the source method that contains parameter names
*
* @param method element from the .class file
* @param source element from the .java file
* @return Formatted string that represents the methods parameters with proper names
*/
public static String printParameters(ExecutableType method, MethodTree source) {
StringJoiner join = new StringJoiner(", ");
for (int i = 0; i < method.getParameterTypes().size(); i++) {
String type = EditHelper.printType(method.getParameterTypes().get(i)).toString();
Name name = source.getParameters().get(i).getName();
join.add(type + " " + name);
}
return join.toString();
}
/**
* Prints parameters with the default names eg. {@code arg0, arg1} this is used when the source
* file of the class isn't found
*
* @param method element to print
* @param source the class file of the method
* @return Formatted String that represents the parameters of this method
*/
public static String printParameters(ExecutableType method, ExecutableElement source) {
StringJoiner join = new StringJoiner(", ");
for (int i = 0; i < method.getParameterTypes().size(); i++) {
String type = EditHelper.printType(method.getParameterTypes().get(i)).toString();
Name name = source.getParameters().get(i).getSimpleName();
join.add(type + " " + name);
}
return join.toString();
}
public static com.github.javaparser.ast.type.Type printType(TypeMirror type) {
return printType(type, false);
}
public static com.github.javaparser.ast.type.Type printType(TypeMirror type, boolean fqn) {
return JavaParserTypesUtil.toType(type);
}
public static String printTypeParameters(List<? extends TypeMirror> arguments) {
StringJoiner join = new StringJoiner(", ");
for (TypeMirror a : arguments) {
join.add(printType(a).toString());
}
return join.toString();
}
public static String printTypeName(TypeElement type) {
return printTypeName(type, false);
}
public static String printTypeName(TypeElement type, boolean fqn) {
if (type.getEnclosingElement() instanceof TypeElement) {
return printTypeName((TypeElement) type.getEnclosingElement(), fqn)
+ "."
+ type.getSimpleName();
}
String s;
if (type.toString().startsWith("<anonymous") && type instanceof Symbol.ClassSymbol) {
Symbol.ClassSymbol symbol = (Symbol.ClassSymbol) type;
s = symbol.type.toString();
} else if (fqn) {
s = type.getQualifiedName().toString();
} else {
s = type.getSimpleName().toString();
}
// anonymous
if (s.isEmpty()) {
s = type.asType().toString();
}
if (s.startsWith("<anonymous")) {
s = s.substring("<anonymous ".length(), s.length() - 1);
}
if (!fqn) {
s = ActionUtil.getSimpleName(s);
}
return s;
}
private static final ClassTreePattern INSIDE_METHOD =
classTree().inside(NewClassTree.class).withParent(method());
public static int indent(JavacTask task, CompilationUnitTree root, Tree leaf) {
Trees trees = Trees.instance(task);
ProcessingContext context = new ProcessingContext();
context.put("trees", trees);
context.put("root", root);
context.put("elements", task.getElements());
if (tree().inside(NewClassTree.class).accepts(leaf, context)) {
TreePath parent = TreeUtil.findParentOfType(trees.getPath(root, leaf), NewClassTree.class);
if (parent != null) {
leaf = parent.getLeaf();
}
}
return indentInternal(task, root, leaf);
}
private static int indentInternal(JavacTask task, CompilationUnitTree root, Tree leaf) {
SourcePositions pos = Trees.instance(task).getSourcePositions();
LineMap lines = root.getLineMap();
long startClass = pos.getStartPosition(root, leaf);
long line = lines.getLineNumber(startClass);
long column = lines.getColumnNumber(startClass);
long startLine = lines.getStartPosition(line);
int indent = (int) (startClass - startLine);
try {
String contents = root.getSourceFile().getCharContent(true).toString();
String[] split = contents.split("\n");
String lineString = split[(int) line - 1];
int newIndent = 0;
int spaceCount = 0;
char[] chars = lineString.toCharArray();
for (char c : chars) {
if (c == '\t') {
newIndent++;
} else if (c == ' ') {
if (spaceCount == 3) {
spaceCount = 0;
newIndent++;
} else {
spaceCount++;
}
} else {
break;
}
}
return newIndent;
} catch (Throwable e) {
// ignored, use the old indent
}
return indent;
}
public static Position insertBefore(JavacTask task, CompilationUnitTree root, Tree member) {
SourcePositions pos = Trees.instance(task).getSourcePositions();
LineMap lines = root.getLineMap();
long start = pos.getStartPosition(root, member);
int line = (int) lines.getLineNumber(start);
return new Position(line - 1, 0);
}
public static Position insertAfter(JavacTask task, CompilationUnitTree root, Tree member) {
SourcePositions pos = Trees.instance(task).getSourcePositions();
LineMap lines = root.getLineMap();
long end = pos.getEndPosition(root, member);
int line = (int) lines.getLineNumber(end);
return new Position(line, 0);
}
public static Position insertAtEndOfClass(
JavacTask task, CompilationUnitTree root, ClassTree leaf) {
SourcePositions pos = Trees.instance(task).getSourcePositions();
LineMap lines = root.getLineMap();
long end = pos.getEndPosition(root, leaf);
int line = (int) lines.getLineNumber(end);
return new Position(line - 1, 0);
}
}
| 15,109 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AddImport.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/AddImport.java | package com.tyron.completion.java.rewrite;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.Trees;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.java.compiler.ParseTask;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.model.Position;
import com.tyron.completion.model.Range;
import com.tyron.completion.model.TextEdit;
import java.io.File;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class AddImport implements JavaRewrite {
private final String className;
private final File currentFile;
private final boolean isStatic;
public AddImport(File currentFile, String className) {
this(currentFile, className, false);
}
public AddImport(File currentFile, String className, boolean isStatic) {
this.className = className;
this.currentFile = currentFile;
this.isStatic = isStatic;
}
@Override
public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
ParseTask task = compiler.parse(currentFile.toPath());
if (ActionUtil.hasImport(task.root, className)) {
return CANCELLED;
}
Position point = insertPosition(task);
String text = "import " + className + ";\n";
TextEdit[] edits = {new TextEdit(new Range(point, point), text)};
return Collections.singletonMap(currentFile.toPath(), edits);
}
public Map<File, TextEdit> getText(ParseTask task) {
if (ActionUtil.hasImport(task.root, className)) {
return Collections.emptyMap();
}
String packageName = className;
if (className.contains(".")) {
packageName = className.substring(0, className.lastIndexOf('.'));
}
if (packageName.equals(String.valueOf(task.root.getPackageName()))) {
return Collections.emptyMap();
}
Position point = insertPosition(task);
String text = "import " + className + ";\n";
if (point.line == 1) {
text = "\nimport " + className + ";\n";
}
TextEdit edit = new TextEdit(new Range(point, point), text);
return Collections.singletonMap(currentFile, edit);
}
private Position insertPosition(ParseTask task) {
List<? extends ImportTree> imports = task.root.getImports();
for (ImportTree i : imports) {
String next = i.getQualifiedIdentifier().toString();
if (className.compareTo(next) < 0) {
return insertBefore(task, i);
}
}
if (!imports.isEmpty()) {
ImportTree last = imports.get(imports.size() - 1);
return insertAfter(task, last);
}
if (task.root.getPackageName() != null) {
return insertAfter(task, task.root.getPackageName());
}
return new Position(0, 0);
}
private Position insertBefore(ParseTask task, Tree i) {
SourcePositions pos = Trees.instance(task.task).getSourcePositions();
long offset = pos.getStartPosition(task.root, i);
int line = (int) task.root.getLineMap().getLineNumber(offset);
return new Position(line - 1, 0);
}
private Position insertAfter(ParseTask task, Tree i) {
SourcePositions pos = Trees.instance(task.task).getSourcePositions();
long offset = pos.getStartPosition(task.root, i);
int line = (int) task.root.getLineMap().getLineNumber(offset);
return new Position(line, 0);
}
}
| 3,381 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaRewrite.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/JavaRewrite.java | package com.tyron.completion.java.rewrite;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.model.Rewrite;
/** A rewrite interface for java operations that needs the {@link CompilerProvider} */
public interface JavaRewrite extends Rewrite<CompilerProvider> {}
| 292 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AddTryCatch.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/AddTryCatch.java | package com.tyron.completion.java.rewrite;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.CatchClause;
import com.github.javaparser.ast.stmt.TryStmt;
import com.google.common.collect.ImmutableMap;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.java.compiler.ParseTask;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.model.Range;
import com.tyron.completion.model.TextEdit;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class AddTryCatch implements JavaRewrite {
private final Path file;
private final String contents;
private final int start;
private final int end;
private final String exceptionName;
public AddTryCatch(Path file, String contents, int start, int end, String exceptionName) {
this.file = file;
this.contents = contents;
this.start = start;
this.end = end;
this.exceptionName = exceptionName;
}
@Override
public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
List<TextEdit> edits = new ArrayList<>();
String newContents = insertColon(contents);
BlockStmt blockStmt = new BlockStmt();
blockStmt.addStatement(newContents);
CatchClause clause =
new CatchClause(
new Parameter(StaticJavaParser.parseType(ActionUtil.getSimpleName(exceptionName)), "e"),
new BlockStmt());
TryStmt stmt = new TryStmt(blockStmt, NodeList.nodeList(clause), null);
String edit = stmt.toString();
Range deleteRange = new Range(start, end);
TextEdit delete = new TextEdit(deleteRange, "");
edits.add(delete);
Range range = new Range(start, start);
TextEdit insert = new TextEdit(range, edit, true);
edits.add(insert);
ParseTask task = compiler.parse(file);
if (!ActionUtil.hasImport(task.root, exceptionName)) {
AddImport addImport = new AddImport(file.toFile(), exceptionName);
Map<Path, TextEdit[]> rewrite = addImport.rewrite(compiler);
TextEdit[] imports = rewrite.get(file);
if (imports != null) {
Collections.addAll(edits, imports);
}
}
return ImmutableMap.of(file, edits.toArray(new TextEdit[0]));
}
private String insertColon(String string) {
if (string.endsWith(")")) {
return string += ";";
}
return string;
}
}
| 2,566 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ImplementAbstractMethods.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/ImplementAbstractMethods.java | package com.tyron.completion.java.rewrite;
import androidx.annotation.Nullable;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.google.common.base.Strings;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.util.JCDiagnostic;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.java.FindNewTypeDeclarationAt;
import com.tyron.completion.java.FindTypeDeclarationAt;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.compiler.ParseTask;
import com.tyron.completion.java.provider.FindHelper;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.java.util.JavaParserUtil;
import com.tyron.completion.model.Position;
import com.tyron.completion.model.Range;
import com.tyron.completion.model.TextEdit;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;
public class ImplementAbstractMethods implements JavaRewrite {
private static final String TAG = ImplementAbstractMethods.class.getSimpleName();
private final String mClassName;
private final String mClassFile;
private final long mPosition;
public ImplementAbstractMethods(String className, String classFile, long lineStart) {
if (className.startsWith("<anonymous")) {
className = className.substring("<anonymous ".length(), className.length() - 1);
}
mClassName = className;
mClassFile = classFile;
mPosition = 0;
}
public ImplementAbstractMethods(JCDiagnostic diagnostic) {
Object[] args = diagnostic.getArgs();
String className = args[0].toString();
if (!className.contains("<anonymous")) {
mClassName = className;
mClassFile = className;
mPosition = 0;
} else {
className = className.substring("<anonymous ".length(), className.length() - 1);
className = className.substring(0, className.indexOf('$'));
mClassFile = className;
mClassName = args[2].toString();
mPosition = diagnostic.getStartPosition();
}
}
@Override
public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
Path file = compiler.findTypeDeclaration(mClassFile);
if (file == JavaCompilerService.NOT_FOUND) {
return Collections.emptyMap();
}
CompilerContainer container = compiler.compile(file);
return container.get(
task -> {
return rewriteInternal(compiler, task, file);
});
}
private Map<Path, TextEdit[]> rewriteInternal(
CompilerProvider compiler, CompileTask task, Path file) {
Elements elements = task.task.getElements();
Types types = task.task.getTypes();
Trees trees = Trees.instance(task.task);
List<TextEdit> edits = new ArrayList<>();
List<TextEdit> importEdits = new ArrayList<>();
Set<String> typesToImport = new HashSet<>();
TypeElement thisClass = elements.getTypeElement(mClassName);
ClassTree thisTree = getClassTree(task, file);
if (thisTree == null) {
thisTree = trees.getTree(thisClass);
}
CompilationUnitTree root = task.root(file);
if (root == null) {
return CANCELLED;
}
TreePath path = trees.getPath(root, thisTree);
Element element = trees.getElement(path);
DeclaredType thisType = (DeclaredType) element.asType();
StringJoiner insertText = new StringJoiner("\n");
int indent = EditHelper.indent(task.task, task.root(), thisTree) + 1;
String tabs = Strings.repeat("\t", indent);
for (Element member : elements.getAllMembers(thisClass)) {
if (member.getKind() == ElementKind.METHOD
&& member.getModifiers().contains(Modifier.ABSTRACT)) {
ExecutableElement method = (ExecutableElement) member;
ExecutableType parameterizedType = (ExecutableType) types.asMemberOf(thisType, method);
typesToImport.addAll(ActionUtil.getTypesToImport(parameterizedType));
MethodTree source = findSource(compiler, task, method);
MethodDeclaration methodDeclaration;
if (source != null) {
methodDeclaration = EditHelper.printMethod(method, parameterizedType, source);
} else {
methodDeclaration = EditHelper.printMethod(method, parameterizedType, method);
}
String text = JavaParserUtil.prettyPrint(methodDeclaration, className -> false);
text = tabs + text.replace("\n", "\n" + tabs);
if (insertText.length() != 0) {
text = "\n" + text;
}
insertText.add(text);
}
}
Position insert = EditHelper.insertAtEndOfClass(task.task, task.root(), thisTree);
insert.line -= 1;
edits.add(new TextEdit(new Range(insert, insert), insertText + "\n"));
edits.addAll(importEdits);
for (String type : typesToImport) {
String fqn = ActionUtil.removeDiamond(type);
if (!ActionUtil.hasImport(task.root(), fqn)) {
JavaRewrite addImport = new AddImport(file.toFile(), fqn);
Map<Path, TextEdit[]> rewrite = addImport.rewrite(compiler);
TextEdit[] textEdits = rewrite.get(file);
if (textEdits != null) {
Collections.addAll(edits, textEdits);
}
}
}
return Collections.singletonMap(file, edits.toArray(new TextEdit[0]));
}
@Nullable
private ClassTree getClassTree(CompileTask task, Path file) {
ClassTree thisTree = null;
CompilationUnitTree root = task.root(file);
if (root == null) {
return null;
}
if (mPosition != 0) {
thisTree = new FindTypeDeclarationAt(task.task).scan(root, mPosition);
}
if (thisTree == null) {
thisTree = new FindNewTypeDeclarationAt(task.task, root).scan(root, mPosition);
}
return thisTree;
}
private MethodTree findSource(
CompilerProvider compiler, CompileTask task, ExecutableElement method) {
TypeElement superClass = (TypeElement) method.getEnclosingElement();
String superClassName = superClass.getQualifiedName().toString();
String methodName = method.getSimpleName().toString();
String[] erasedParameterTypes = FindHelper.erasedParameterTypes(task, method);
Optional<JavaFileObject> sourceFile = compiler.findAnywhere(superClassName);
if (!sourceFile.isPresent()) return null;
ParseTask parse = compiler.parse(sourceFile.get());
return FindHelper.findMethod(parse, superClassName, methodName, erasedParameterTypes);
}
}
| 7,223 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AddException.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/AddException.java | package com.tyron.completion.java.rewrite;
import com.google.common.collect.ImmutableMap;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.Trees;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.provider.FindHelper;
import com.tyron.completion.model.Range;
import com.tyron.completion.model.TextEdit;
import java.nio.file.Path;
import java.util.Map;
import javax.lang.model.element.ExecutableElement;
public class AddException implements JavaRewrite {
private final String className;
private final String methodName;
private final String[] erasedParameterTypes;
private String exceptionType;
public AddException(
String className, String methodName, String[] erasedParameterTypes, String exceptionType) {
this.className = className;
this.methodName = methodName;
this.erasedParameterTypes = erasedParameterTypes;
this.exceptionType = exceptionType;
}
@Override
public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
Path file = compiler.findTypeDeclaration(className);
if (file == CompilerProvider.NOT_FOUND) {
return CANCELLED;
}
CompilerContainer container = compiler.compile(file);
return container.get(
task -> {
CompilationUnitTree root = task.root(file);
if (root == null) {
return CANCELLED;
}
Trees trees = Trees.instance(task.task);
ExecutableElement methodElement =
FindHelper.findMethod(task, className, methodName, erasedParameterTypes);
MethodTree methodTree = trees.getTree(methodElement);
SourcePositions pos = trees.getSourcePositions();
long startBody = pos.getStartPosition(root, methodTree.getBody());
String packageName = "";
String simpleName = exceptionType;
int lastDot = simpleName.lastIndexOf('.');
if (lastDot != -1) {
packageName = exceptionType.substring(0, lastDot);
simpleName = exceptionType.substring(lastDot + 1);
}
String insertText;
if (methodTree.getThrows().isEmpty()) {
insertText = " throws " + simpleName + " ";
} else {
insertText = ", " + simpleName + " ";
}
TextEdit insertThrows = new TextEdit(new Range(startBody - 1, startBody - 1), insertText);
return ImmutableMap.of(file, new TextEdit[] {insertThrows});
});
}
}
| 2,629 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AddCatchClause.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/AddCatchClause.java | package com.tyron.completion.java.rewrite;
import com.google.common.collect.ImmutableMap;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.java.compiler.ParseTask;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.model.Range;
import com.tyron.completion.model.TextEdit;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class AddCatchClause implements JavaRewrite {
private final Path file;
private final int start;
private final String exceptionName;
public AddCatchClause(Path file, int start, String exceptionName) {
this.file = file;
this.start = start;
this.exceptionName = exceptionName;
}
@Override
public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
List<TextEdit> edits = new ArrayList<>();
String finalString = " catch (" + ActionUtil.getSimpleName(exceptionName) + " e) { }";
Range range = new Range(start, start);
TextEdit edit = new TextEdit(range, finalString, true);
edits.add(edit);
ParseTask task = compiler.parse(file);
if (!ActionUtil.hasImport(task.root, exceptionName)) {
AddImport addImport = new AddImport(file.toFile(), exceptionName);
Map<Path, TextEdit[]> rewrite = addImport.rewrite(compiler);
TextEdit[] imports = rewrite.get(file);
if (imports != null) {
Collections.addAll(edits, imports);
}
}
return ImmutableMap.of(file, edits.toArray(new TextEdit[0]));
}
}
| 1,559 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ConvertToLambda.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/ConvertToLambda.java | package com.tyron.completion.java.rewrite;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.model.TextEdit;
import java.nio.file.Path;
import java.util.Map;
/** Converts an anonymous class into a lambda expression */
public class ConvertToLambda implements JavaRewrite {
@Override
public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
return null;
}
}
| 407 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
RewriteNotSupported.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/RewriteNotSupported.java | package com.tyron.completion.java.rewrite;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.model.TextEdit;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
public class RewriteNotSupported implements JavaRewrite {
@Override
public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
return Collections.emptyMap();
}
}
| 398 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
OverrideInheritedMethod.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/rewrite/OverrideInheritedMethod.java | package com.tyron.completion.java.rewrite;
import com.google.common.base.Strings;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.builder.model.SourceFileObject;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.java.FindNewTypeDeclarationAt;
import com.tyron.completion.java.FindTypeDeclarationAt;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.compiler.ParseTask;
import com.tyron.completion.java.provider.FindHelper;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.java.util.PrintHelper;
import com.tyron.completion.model.Position;
import com.tyron.completion.model.Range;
import com.tyron.completion.model.TextEdit;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;
public class OverrideInheritedMethod implements JavaRewrite {
final String superClassName, methodName;
final String[] erasedParameterTypes;
final Path file;
final int insertPosition;
private final SourceFileObject sourceFileObject;
public OverrideInheritedMethod(
String superClassName,
String methodName,
String[] erasedParameterTypes,
Path file,
int insertPosition) {
this.superClassName = superClassName;
this.methodName = methodName;
this.erasedParameterTypes = erasedParameterTypes;
this.file = file;
this.sourceFileObject = null;
this.insertPosition = insertPosition;
}
public OverrideInheritedMethod(
String superClassName,
String methodName,
String[] erasedParameterTypes,
SourceFileObject file,
int insertPosition) {
this.superClassName = superClassName;
this.methodName = methodName;
this.erasedParameterTypes = erasedParameterTypes;
this.file = null;
this.sourceFileObject = file;
this.insertPosition = insertPosition;
}
@Override
public Map<Path, TextEdit[]> rewrite(CompilerProvider compiler) {
List<TextEdit> edits = new ArrayList<>();
Position insertPoint = insertNearCursor(compiler);
if (insertPoint == Position.NONE) {
return CANCELLED;
}
CompilerContainer container =
sourceFileObject == null
? compiler.compile(file)
: compiler.compile(Collections.singletonList(sourceFileObject));
return container.get(
task -> {
Types types = task.task.getTypes();
Trees trees = Trees.instance(task.task);
ExecutableElement superMethod =
FindHelper.findMethod(task, superClassName, methodName, erasedParameterTypes);
if (superMethod == null) {
return CANCELLED;
}
CompilationUnitTree root = task.root();
if (root == null) {
return CANCELLED;
}
ClassTree thisTree =
new FindTypeDeclarationAt(task.task).scan(root, (long) insertPosition);
TreePath thisPath = trees.getPath(root, thisTree);
TypeElement thisClass = (TypeElement) trees.getElement(thisPath);
ExecutableType parameterizedType =
(ExecutableType) types.asMemberOf((DeclaredType) thisClass.asType(), superMethod);
int indent = EditHelper.indent(task.task, root, thisTree) + 1;
Set<String> typesToImport = ActionUtil.getTypesToImport(parameterizedType);
Optional<JavaFileObject> sourceFile = compiler.findAnywhere(superClassName);
String text;
if (sourceFile.isPresent()) {
ParseTask parse = compiler.parse(sourceFile.get());
MethodTree source =
FindHelper.findMethod(parse, superClassName, methodName, erasedParameterTypes);
if (source == null) {
text = PrintHelper.printMethod(superMethod, parameterizedType, superMethod);
} else {
text = PrintHelper.printMethod(superMethod, parameterizedType, source);
}
} else {
text = PrintHelper.printMethod(superMethod, parameterizedType, superMethod);
}
String tabs = Strings.repeat("\t", indent);
text = tabs + text.replace("\n", "\n" + tabs) + "\n\n";
edits.add(new TextEdit(new Range(insertPoint, insertPoint), text));
File source =
file != null
? file.toFile()
: Objects.requireNonNull(sourceFileObject).mFile.toFile();
for (String s : typesToImport) {
if (!ActionUtil.hasImport(root, s)) {
JavaRewrite addImport = new AddImport(source, s);
Map<Path, TextEdit[]> rewrite = addImport.rewrite(compiler);
TextEdit[] textEdits = rewrite.get(source.toPath());
if (textEdits != null) {
Collections.addAll(edits, textEdits);
}
}
}
return Collections.singletonMap(source.toPath(), edits.toArray(new TextEdit[0]));
});
}
private Position insertNearCursor(CompilerProvider compiler) {
ParseTask task = file != null ? compiler.parse(file) : compiler.parse(sourceFileObject);
ClassTree parent = new FindTypeDeclarationAt(task.task).scan(task.root, (long) insertPosition);
if (parent == null) {
parent =
new FindNewTypeDeclarationAt(task.task, task.root).scan(task.root, (long) insertPosition);
}
Position next = nextMember(task, parent);
if (next != Position.NONE) {
return next;
}
return EditHelper.insertAtEndOfClass(task.task, task.root, parent);
}
private Position nextMember(ParseTask task, ClassTree parent) {
SourcePositions pos = Trees.instance(task.task).getSourcePositions();
if (parent != null) {
for (Tree member : parent.getMembers()) {
long start = pos.getStartPosition(task.root, member);
if (start > insertPosition) {
int line = (int) task.root.getLineMap().getLineNumber(start);
return new Position(line - 1, 0);
}
}
}
return Position.NONE;
}
}
| 6,672 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CommonJavaContextKeys.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/CommonJavaContextKeys.java | package com.tyron.completion.java.action;
import com.sun.source.util.TreePath;
import com.tyron.completion.java.compiler.JavaCompilerService;
import org.jetbrains.kotlin.com.intellij.openapi.util.Key;
public class CommonJavaContextKeys {
/** The current TreePath in the editor based on the current cursor */
public static final Key<TreePath> CURRENT_PATH = Key.create("currentPath");
public static final Key<JavaCompilerService> COMPILER = Key.create("compiler");
}
| 476 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FindMethodDeclarationAt.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/FindMethodDeclarationAt.java | package com.tyron.completion.java.action;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;
public class FindMethodDeclarationAt extends TreeScanner<MethodTree, Long> {
private final SourcePositions mPos;
private CompilationUnitTree mCompilationUnit;
public FindMethodDeclarationAt(JavacTask task) {
mPos = Trees.instance(task).getSourcePositions();
}
@Override
public MethodTree visitCompilationUnit(CompilationUnitTree compilationUnitTree, Long aLong) {
mCompilationUnit = compilationUnitTree;
return super.visitCompilationUnit(compilationUnitTree, aLong);
}
@Override
public MethodTree visitMethod(MethodTree methodTree, Long find) {
MethodTree smaller = super.visitMethod(methodTree, find);
if (smaller != null) {
return smaller;
}
if (mPos.getStartPosition(mCompilationUnit, methodTree) <= find
&& find < mPos.getEndPosition(mCompilationUnit, methodTree)) {
return methodTree;
}
return null;
}
@Override
public MethodTree reduce(MethodTree r1, MethodTree r2) {
if (r1 != null) return r1;
return r2;
}
}
| 1,300 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FindCurrentPath.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/FindCurrentPath.java | package com.tyron.completion.java.action;
import android.util.Pair;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ErroneousTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.SwitchTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.Trees;
import com.sun.tools.javac.tree.JCTree;
import java.util.List;
/**
* Scanner to retrieve the current {@link TreePath} given the cursor position each visit methods
* checks if the current tree is in between the cursor
*/
public class FindCurrentPath extends TreePathScanner<TreePath, Pair<Long, Long>> {
private final JavacTask task;
private final SourcePositions mPos;
private CompilationUnitTree mCompilationUnit;
public FindCurrentPath(JavacTask task) {
this.task = task;
mPos = Trees.instance(task).getSourcePositions();
}
public TreePath scan(Tree tree, long start) {
return scan(tree, start, start);
}
public TreePath scan(Tree tree, long start, long end) {
return super.scan(tree, Pair.create(start, end));
}
@Override
public TreePath visitCompilationUnit(
CompilationUnitTree compilationUnitTree, Pair<Long, Long> find) {
mCompilationUnit = compilationUnitTree;
return super.visitCompilationUnit(compilationUnitTree, find);
}
@Override
public TreePath visitImport(ImportTree importTree, Pair<Long, Long> longLongPair) {
if (isInside(importTree, longLongPair)) {
return getCurrentPath();
}
return super.visitImport(importTree, longLongPair);
}
@Override
public TreePath visitClass(ClassTree classTree, Pair<Long, Long> aLong) {
TreePath smaller = super.visitClass(classTree, aLong);
if (smaller != null) {
return smaller;
}
if (isInside(classTree, aLong)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitMethod(MethodTree methodTree, Pair<Long, Long> aLong) {
TreePath smaller = super.visitMethod(methodTree, aLong);
if (smaller != null) {
return smaller;
}
if (isInside(methodTree, aLong)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitMethodInvocation(MethodInvocationTree tree, Pair<Long, Long> cursor) {
TreePath smaller = super.visitMethodInvocation(tree, cursor);
if (smaller != null) {
return smaller;
}
if (tree instanceof JCTree.JCMethodInvocation) {
if (isInside(tree, cursor)) {
return getCurrentPath();
}
}
return null;
}
@Override
public TreePath visitMemberSelect(MemberSelectTree t, Pair<Long, Long> find) {
TreePath smaller = super.visitMemberSelect(t, find);
if (smaller != null) {
return smaller;
}
if (isInside(t, find)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitMemberReference(MemberReferenceTree t, Pair<Long, Long> find) {
TreePath smaller = super.visitMemberReference(t, find);
if (smaller != null) {
return smaller;
}
if (isInside(t, find)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitExpressionStatement(ExpressionStatementTree t, Pair<Long, Long> find) {
TreePath smaller = super.visitExpressionStatement(t, find);
if (smaller != null) {
return smaller;
}
if (isInside(t, find)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitPrimitiveType(PrimitiveTypeTree t, Pair<Long, Long> find) {
if (isInside(t, find)) {
return getCurrentPath();
}
return super.visitPrimitiveType(t, find);
}
@Override
public TreePath visitIdentifier(IdentifierTree t, Pair<Long, Long> find) {
if (isInside(t, find)) {
return getCurrentPath();
}
return super.visitIdentifier(t, find);
}
@Override
public TreePath visitVariable(VariableTree t, Pair<Long, Long> find) {
TreePath smaller = super.visitVariable(t, find);
if (smaller != null) {
return smaller;
}
if (isInside(t, find)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitBlock(BlockTree t, Pair<Long, Long> find) {
TreePath smaller = super.visitBlock(t, find);
if (smaller != null) {
return smaller;
}
if (isInside(t, find)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitLambdaExpression(LambdaExpressionTree t, Pair<Long, Long> find) {
TreePath smaller = super.visitLambdaExpression(t, find);
if (smaller != null) {
return smaller;
}
if (isInside(t, find)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitLiteral(LiteralTree literalTree, Pair<Long, Long> aLong) {
if (isInside(literalTree, aLong)) {
return getCurrentPath();
}
return super.visitLiteral(literalTree, aLong);
}
@Override
public TreePath visitNewClass(NewClassTree t, Pair<Long, Long> find) {
TreePath smaller = super.visitNewClass(t, find);
if (smaller != null) {
return smaller;
}
if (isInside(t, find) && !isInside(t.getClassBody(), find)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitSwitch(SwitchTree switchTree, Pair<Long, Long> longLongPair) {
TreePath smaller = super.visitSwitch(switchTree, longLongPair);
if (smaller != null) {
return smaller;
}
if (isInside(switchTree, longLongPair)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitCase(CaseTree caseTree, Pair<Long, Long> longLongPair) {
TreePath smaller = super.visitCase(caseTree, longLongPair);
if (smaller != null) {
return smaller;
}
if (isInside(caseTree, longLongPair)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitErroneous(ErroneousTree t, Pair<Long, Long> find) {
List<? extends Tree> errorTrees = t.getErrorTrees();
if (errorTrees == null) {
return null;
}
for (Tree error : errorTrees) {
TreePath scan = super.scan(error, find);
if (scan != null) {
return scan;
}
}
return null;
}
@Override
public TreePath reduce(TreePath r1, TreePath r2) {
if (r1 != null) return r1;
return r2;
}
private boolean isInside(Tree tree, Pair<Long, Long> find) {
long start = mPos.getStartPosition(mCompilationUnit, tree);
long end = mPos.getEndPosition(mCompilationUnit, tree);
return start <= find.first && find.second <= end;
}
}
| 7,414 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
OverrideInheritedMethodsAction.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/context/OverrideInheritedMethodsAction.java | package com.tyron.completion.java.action.context;
import static com.tyron.completion.java.util.DiagnosticUtil.MethodPtr;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.WorkerThread;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.sun.source.tree.ClassTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.actions.ActionPlaces;
import com.tyron.actions.AnAction;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.actions.Presentation;
import com.tyron.builder.model.SourceFileObject;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.FileManager;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.builder.project.api.Module;
import com.tyron.common.ApplicationProvider;
import com.tyron.common.util.AndroidUtilities;
import com.tyron.completion.java.R;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.drawable.CircleDrawable;
import com.tyron.completion.java.rewrite.JavaRewrite;
import com.tyron.completion.java.rewrite.OverrideInheritedMethod;
import com.tyron.completion.java.util.CompletionItemFactory;
import com.tyron.completion.java.util.PrintHelper;
import com.tyron.completion.model.DrawableKind;
import com.tyron.completion.progress.ProgressManager;
import com.tyron.completion.util.RewriteUtil;
import com.tyron.editor.Editor;
import com.tyron.ui.treeview.TreeNode;
import com.tyron.ui.treeview.TreeView;
import com.tyron.ui.treeview.base.BaseNodeViewBinder;
import com.tyron.ui.treeview.base.BaseNodeViewFactory;
import java.io.File;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.util.Elements;
import org.checkerframework.checker.nullness.qual.Nullable;
public class OverrideInheritedMethodsAction extends AnAction {
public static final String ID = "javaOverrideInheritedMethodsAction";
@Override
public void update(@NonNull AnActionEvent event) {
Presentation presentation = event.getPresentation();
presentation.setVisible(false);
if (!ActionPlaces.EDITOR.equals(event.getPlace())) {
return;
}
TreePath currentPath = event.getData(CommonJavaContextKeys.CURRENT_PATH);
if (currentPath == null) {
return;
}
if (!(currentPath.getLeaf() instanceof ClassTree)) {
return;
}
JavaCompilerService compiler = event.getData(CommonJavaContextKeys.COMPILER);
if (compiler == null) {
return;
}
presentation.setVisible(true);
presentation.setText(
event.getDataContext().getString(R.string.menu_quickfix_override_inherited_methods_title));
}
@Override
public void actionPerformed(@NonNull AnActionEvent e) {
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
Activity activity = e.getRequiredData(CommonDataKeys.ACTIVITY);
File file = e.getRequiredData(CommonDataKeys.FILE);
Project project = e.getRequiredData(CommonDataKeys.PROJECT);
JavaCompilerService compiler = e.getRequiredData(CommonJavaContextKeys.COMPILER);
TreePath currentPath = e.getRequiredData(CommonJavaContextKeys.CURRENT_PATH);
Module module = project.getModule(file);
if (module == null) {
AndroidUtilities.showSimpleAlert(
e.getDataContext(), "Error", "The file is not part of any modules.");
return;
}
FileManager fileManager = module.getFileManager();
Optional<CharSequence> fileContent = fileManager.getFileContent(file);
if (!fileManager.isOpened(file) || !fileContent.isPresent()) {
AndroidUtilities.showSimpleAlert(
e.getDataContext(), "Error", "The file is not currently opened in any editors.");
return;
}
SourceFileObject sourceFileObject =
new SourceFileObject(file.toPath(), (JavaModule) module, Instant.now());
ListenableFuture<List<MethodPtr>> future =
ProgressManager.getInstance()
.computeNonCancelableAsync(
() -> {
List<MethodPtr> pointers =
performInternal(compiler, sourceFileObject, currentPath);
Collections.reverse(pointers);
return Futures.immediateFuture(pointers);
});
ProgressDialog dialog = new ProgressDialog(e.getDataContext());
Runnable showLoadingRunnable = dialog::show;
// show a progress bar if task is still running after 2 seconds
ProgressManager.getInstance().runLater(showLoadingRunnable, 2000);
Futures.addCallback(
future,
new FutureCallback<List<MethodPtr>>() {
@Override
public void onSuccess(@Nullable List<MethodPtr> pointers) {
if (activity.isFinishing() || activity.isDestroyed()) {
return;
}
dialog.dismiss();
if (pointers == null) {
return;
}
OverrideInheritedMethodsAction.this.onSuccess(
pointers, showLoadingRunnable, e, sourceFileObject, file, editor, compiler);
}
@Override
public void onFailure(@NonNull Throwable t) {
if (activity.isFinishing() || activity.isDestroyed()) {
return;
}
dialog.dismiss();
ProgressManager.getInstance().cancelRunLater(showLoadingRunnable);
AndroidUtilities.showSimpleAlert(e.getDataContext(), "Error", t.getMessage());
}
},
ContextCompat.getMainExecutor(e.getDataContext()));
}
private void onSuccess(
@NonNull List<MethodPtr> pointers,
Runnable showLoadingRunnable,
@NonNull AnActionEvent e,
SourceFileObject sourceFileObject,
File file,
Editor editor,
JavaCompilerService compiler) {
ProgressManager.getInstance().cancelRunLater(showLoadingRunnable);
TreeView<OverrideNode> treeView = new TreeView<>(e.getDataContext(), buildTreeNode(pointers));
treeView.getView().setPaddingRelative(0, AndroidUtilities.dp(8), 0, 0);
OverrideNodeViewFactory factory = new OverrideNodeViewFactory();
treeView.setAdapter(factory);
AlertDialog dialog =
new MaterialAlertDialogBuilder(e.getDataContext())
.setTitle(R.string.menu_quickfix_implement_abstract_methods_title)
.setView(treeView.getView())
.setNegativeButton(android.R.string.cancel, null)
.show();
factory.setOnTreeNodeClickListener(
(node, expand) -> {
if (node.isLeaf()) {
dialog.dismiss();
OverrideNode value = node.getValue();
MethodPtr ptr = value.getMethodPtr();
JavaRewrite rewrite =
new OverrideInheritedMethod(
ptr.className,
ptr.methodName,
ptr.erasedParameterTypes,
sourceFileObject,
editor.getCaret().getStart());
RewriteUtil.performRewrite(editor, file, compiler, rewrite);
}
});
}
@WorkerThread
private List<MethodPtr> performInternal(
JavaCompilerService compiler, SourceFileObject file, TreePath currentPath) {
CompilerContainer container = compiler.compile(Collections.singletonList(file));
return container.get(
task -> {
Trees trees = Trees.instance(task.task);
Element classElement = trees.getElement(currentPath);
Elements elements = task.task.getElements();
List<MethodPtr> methodPtrs = new ArrayList<>();
for (Element member : elements.getAllMembers((TypeElement) classElement)) {
if (member.getModifiers().contains(Modifier.FINAL)) {
continue;
}
if (member.getModifiers().contains(Modifier.STATIC)) {
continue;
}
if (member.getKind() != ElementKind.METHOD) {
continue;
}
ExecutableElement method = (ExecutableElement) member;
TypeElement methodSource = (TypeElement) member.getEnclosingElement();
if (methodSource.equals(classElement)) {
continue;
}
MethodPtr ptr = new MethodPtr(task.task, method);
methodPtrs.add(ptr);
}
return methodPtrs;
});
}
private static TreeNode<OverrideNode> buildTreeNode(List<MethodPtr> methodPtrs) {
Map<String, List<MethodPtr>> classToPtr = new LinkedHashMap<>();
for (MethodPtr methodPtr : methodPtrs) {
classToPtr.compute(
methodPtr.className,
(s, list) -> {
if (list == null) {
list = new ArrayList<>();
}
list.add(methodPtr);
return list;
});
}
TreeNode<OverrideNode> root = TreeNode.root();
for (String key : classToPtr.keySet()) {
List<MethodPtr> methods = classToPtr.get(key);
if (methods != null && !methods.isEmpty()) {
OverrideNode classNode = new OverrideNode(methods.iterator().next(), false);
TreeNode<OverrideNode> classTreeNode = new TreeNode<>(classNode, 1);
classTreeNode.setExpanded(true);
for (MethodPtr method : methods) {
classTreeNode.addChild(new TreeNode<>(new OverrideNode(method, true), 2));
}
root.addChild(classTreeNode);
}
}
return root;
}
private static class OverrideNode {
private final MethodPtr ptr;
private final boolean isMethod;
public OverrideNode(MethodPtr value, boolean method) {
ptr = value;
isMethod = method;
}
public boolean isMethod() {
return isMethod;
}
public MethodPtr getMethodPtr() {
return ptr;
}
}
private static class OverrideNodeViewFactory extends BaseNodeViewFactory<OverrideNode> {
private TreeView.OnTreeNodeClickListener<OverrideNode> listener;
@Override
public BaseNodeViewBinder<OverrideNode> getNodeViewBinder(View view, int viewType) {
return new OverrideNodeViewBinder(view, listener);
}
@Override
public int getNodeLayoutId(int level) {
return R.layout.override_node_item;
}
public void setOnTreeNodeClickListener(
TreeView.OnTreeNodeClickListener<OverrideNode> listener) {
this.listener = listener;
}
}
private static class OverrideNodeViewBinder extends BaseNodeViewBinder<OverrideNode> {
private final View root;
private final TextView text;
private final ImageView icon;
private final ImageView arrow;
private final TreeView.OnTreeNodeClickListener<OverrideNode> listener;
public OverrideNodeViewBinder(
View itemView, TreeView.OnTreeNodeClickListener<OverrideNode> listener) {
super(itemView);
root = itemView;
text = itemView.findViewById(R.id.override_node_title);
arrow = itemView.findViewById(R.id.arrow);
icon = itemView.findViewById(R.id.icon);
this.listener = listener;
}
@Override
public void bindView(TreeNode<OverrideNode> treeNode) {
DisplayMetrics displayMetrics =
ApplicationProvider.getApplicationContext().getResources().getDisplayMetrics();
int startMargin =
treeNode.getLevel()
* Math.round(
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, displayMetrics));
((ViewGroup.MarginLayoutParams) root.getLayoutParams()).setMarginStart(startMargin);
OverrideNode value = treeNode.getValue();
MethodPtr ptr = value.getMethodPtr();
if (value.isMethod()) {
String methodLabel =
CompletionItemFactory.getMethodLabel(ptr.method, (ExecutableType) ptr.method.asType());
methodLabel += ":" + PrintHelper.printType(ptr.method.getReturnType());
text.setText(methodLabel);
icon.setImageDrawable(new CircleDrawable(DrawableKind.Method, true));
arrow.setImageDrawable(null);
} else {
text.setText(ptr.className);
icon.setImageDrawable(new CircleDrawable(DrawableKind.Class, true));
arrow.setVisibility(View.VISIBLE);
}
arrow.setRotation(treeNode.isExpanded() ? 0 : 270);
}
@Override
public void onNodeToggled(TreeNode<OverrideNode> treeNode, boolean expand) {
super.onNodeToggled(treeNode, expand);
if (expand) {
arrow.setRotation(270);
arrow.animate().rotationBy(90).setDuration(150L).start();
} else {
arrow.setRotation(0);
arrow.animate().rotationBy(-90).setDuration(150L).start();
}
listener.onTreeNodeClicked(treeNode, expand);
}
@Override
public boolean onNodeLongClicked(View view, TreeNode<OverrideNode> treeNode, boolean expanded) {
return super.onNodeLongClicked(view, treeNode, expanded);
}
}
}
| 13,880 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
IntroduceLocalVariableAction.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/context/IntroduceLocalVariableAction.java | package com.tyron.completion.java.action.context;
import androidx.annotation.NonNull;
import com.sun.source.tree.ErroneousTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.code.Type;
import com.tyron.actions.ActionPlaces;
import com.tyron.actions.AnAction;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.actions.Presentation;
import com.tyron.completion.java.R;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.rewrite.IntroduceLocalVariable;
import com.tyron.completion.java.rewrite.JavaRewrite;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.util.RewriteUtil;
import com.tyron.editor.Editor;
import java.io.File;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
public class IntroduceLocalVariableAction extends AnAction {
public static final String ID = "javaIntroduceLocalVariableAction";
@Override
public void update(@NonNull AnActionEvent event) {
Presentation presentation = event.getPresentation();
presentation.setVisible(false);
if (!ActionPlaces.EDITOR.equals(event.getPlace())) {
return;
}
Editor editor = event.getData(CommonDataKeys.EDITOR);
if (editor == null) {
return;
}
JavaCompilerService compiler = event.getData(CommonJavaContextKeys.COMPILER);
if (compiler == null) {
return;
}
File file = event.getData(CommonDataKeys.FILE);
if (file == null) {
return;
}
TreePath currentPath = event.getData(CommonJavaContextKeys.CURRENT_PATH);
if (currentPath == null) {
return;
}
if (ActionUtil.canIntroduceLocalVariable(currentPath) == null) {
return;
}
presentation.setVisible(true);
presentation.setText(
event.getDataContext().getString(R.string.menu_quickfix_introduce_local_variable_title));
}
@Override
public void actionPerformed(@NonNull AnActionEvent e) {
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
TreePath currentPath = e.getRequiredData(CommonJavaContextKeys.CURRENT_PATH);
File file = e.getRequiredData(CommonDataKeys.FILE);
JavaCompilerService compiler = e.getRequiredData(CommonJavaContextKeys.COMPILER);
CompilerContainer cachedContainer = compiler.getCachedContainer();
JavaRewrite rewrite =
cachedContainer.get(
task -> {
if (task != null) {
TreePath path = ActionUtil.canIntroduceLocalVariable(currentPath);
return performInternal(task, path, file);
}
return null;
});
if (rewrite != null) {
RewriteUtil.performRewrite(editor, file, compiler, rewrite);
}
}
private JavaRewrite performInternal(CompileTask task, TreePath path, File file) {
if (path.getLeaf().getKind() == Tree.Kind.ERRONEOUS) {
ErroneousTree leaf = (ErroneousTree) path.getLeaf();
List<? extends Tree> errorTrees = leaf.getErrorTrees();
if (errorTrees != null && !errorTrees.isEmpty()) {
path = new TreePath(path.getParentPath(), errorTrees.get(0));
}
}
Trees trees = task.getTrees();
Element element = trees.getElement(path);
if (element == null) {
return null;
}
TypeMirror typeMirror = trees.getTypeMirror(path);
if (typeMirror == null || typeMirror.getKind() == TypeKind.ERROR) {
// information is incomplete and type cannot be determined, default to Object
typeMirror = task.task.getElements().getTypeElement("java.lang.Object").asType();
}
if (typeMirror != null) {
if (typeMirror.getKind() == TypeKind.TYPEVAR) {
if (((Type.TypeVar) typeMirror).isCaptured()) {
typeMirror = ((Type.TypeVar) typeMirror).getUpperBound();
}
}
if (typeMirror.getKind() == TypeKind.EXECUTABLE) {
// use the return type of the method
typeMirror = ((ExecutableType) typeMirror).getReturnType();
}
return rewrite(typeMirror, trees, path, file, element.getSimpleName().toString());
}
if (element instanceof ExecutableElement) {
TypeMirror returnType =
ActionUtil.getReturnType(task.task, path, (ExecutableElement) element);
if (returnType != null) {
return rewrite(returnType, trees, path, file, element.getSimpleName().toString());
}
}
return null;
}
private JavaRewrite rewrite(
TypeMirror type, Trees trees, TreePath path, File file, String methodName) {
SourcePositions pos = trees.getSourcePositions();
long startPosition = pos.getStartPosition(path.getCompilationUnit(), path.getLeaf());
return new IntroduceLocalVariable(file.toPath(), methodName, type, startPosition);
}
}
| 5,245 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ViewJavaDocAction.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/context/ViewJavaDocAction.java | package com.tyron.completion.java.action.context;
import android.app.AlertDialog;
import androidx.annotation.NonNull;
import com.sun.source.util.TreePath;
import com.tyron.actions.ActionPlaces;
import com.tyron.actions.AnAction;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.actions.Presentation;
import com.tyron.completion.java.R;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.hover.HoverProvider;
import com.tyron.editor.Editor;
import java.io.File;
import java.util.List;
public class ViewJavaDocAction extends AnAction {
@Override
public void update(@NonNull AnActionEvent event) {
Presentation presentation = event.getPresentation();
presentation.setVisible(false);
if (!ActionPlaces.EDITOR.equals(event.getPlace())) {
return;
}
File file = event.getData(CommonDataKeys.FILE);
if (file == null) {
return;
}
Editor editor = event.getData(CommonDataKeys.EDITOR);
if (editor == null) {
return;
}
TreePath currentPath = event.getData(CommonJavaContextKeys.CURRENT_PATH);
if (currentPath == null) {
return;
}
JavaCompilerService compiler = event.getData(CommonJavaContextKeys.COMPILER);
if (compiler == null) {
return;
}
HoverProvider hoverProvider = new HoverProvider(compiler);
List<String> strings =
hoverProvider.hover(file.toPath().getFileName(), editor.getCaret().getStart());
if (strings.isEmpty()) {
return;
}
presentation.setVisible(true);
presentation.setText(event.getDataContext().getString(R.string.menu_action_view_javadoc_title));
}
@Override
public void actionPerformed(@NonNull AnActionEvent e) {
Editor editor = e.getData(CommonDataKeys.EDITOR);
File file = e.getData(CommonDataKeys.FILE);
JavaCompilerService compiler = e.getData(CommonJavaContextKeys.COMPILER);
HoverProvider hoverProvider = new HoverProvider(compiler);
List<String> strings = hoverProvider.hover(file.toPath(), editor.getCaret().getStart());
String title = e.getDataContext().getString(R.string.menu_action_view_javadoc_title);
new AlertDialog.Builder(e.getDataContext())
.setTitle(title)
.setMessage(strings.get(0))
.setPositiveButton(R.string.menu_close, null)
.show();
}
}
| 2,449 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AddCatchClauseAction.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/quickfix/AddCatchClauseAction.java | package com.tyron.completion.java.action.quickfix;
import androidx.annotation.NonNull;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.TryTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.actions.Presentation;
import com.tyron.common.util.ThreadUtil;
import com.tyron.completion.java.R;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.rewrite.AddCatchClause;
import com.tyron.completion.java.rewrite.JavaRewrite;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.java.util.DiagnosticUtil;
import com.tyron.completion.util.RewriteUtil;
import com.tyron.editor.Editor;
import java.io.File;
import java.util.Locale;
import javax.tools.Diagnostic;
public class AddCatchClauseAction extends ExceptionsQuickFix {
public static final String ID = "javaAddCatchClauseQuickFix";
@Override
public void update(@NonNull AnActionEvent event) {
super.update(event);
Presentation presentation = event.getPresentation();
if (!presentation.isVisible()) {
return;
}
presentation.setVisible(false);
Diagnostic<?> diagnostic = event.getData(CommonDataKeys.DIAGNOSTIC);
if (diagnostic == null) {
return;
}
TreePath surroundingPath =
ActionUtil.findSurroundingPath(event.getData(CommonJavaContextKeys.CURRENT_PATH));
if (surroundingPath == null) {
return;
}
if (!(surroundingPath.getLeaf() instanceof TryTree)) {
return;
}
presentation.setEnabled(true);
presentation.setVisible(true);
presentation.setText(
event.getDataContext().getString(R.string.menu_quickfix_add_catch_clause_title));
}
@Override
public void actionPerformed(@NonNull AnActionEvent e) {
Editor editor = e.getData(CommonDataKeys.EDITOR);
File file = e.getData(CommonDataKeys.FILE);
JavaCompilerService compiler = e.getData(CommonJavaContextKeys.COMPILER);
Diagnostic<?> diagnostic = e.getData(CommonDataKeys.DIAGNOSTIC);
TreePath currentPath = e.getData(CommonJavaContextKeys.CURRENT_PATH);
TreePath surroundingPath = ActionUtil.findSurroundingPath(currentPath);
String exceptionName =
DiagnosticUtil.extractExceptionName(diagnostic.getMessage(Locale.ENGLISH));
if (surroundingPath == null) {
return;
}
ThreadUtil.runOnBackgroundThread(
() -> {
JavaRewrite r = performInternal(file, exceptionName, surroundingPath);
RewriteUtil.performRewrite(editor, file, compiler, r);
});
}
private JavaRewrite performInternal(File file, String exceptionName, TreePath surroundingPath) {
CompilationUnitTree root = surroundingPath.getCompilationUnit();
JCTree.JCCompilationUnit compilationUnit = (JCTree.JCCompilationUnit) root;
EndPosTable endPositions = compilationUnit.endPositions;
TryTree tryTree = (TryTree) surroundingPath.getLeaf();
CatchTree catchTree = tryTree.getCatches().get(tryTree.getCatches().size() - 1);
JCTree.JCCatch jcCatch = (JCTree.JCCatch) catchTree;
int start = (int) jcCatch.getEndPosition(endPositions);
return new AddCatchClause(file.toPath(), start, exceptionName);
}
}
| 3,470 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ExceptionsQuickFix.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/quickfix/ExceptionsQuickFix.java | package com.tyron.completion.java.action.quickfix;
import androidx.annotation.NonNull;
import com.sun.source.util.TreePath;
import com.tyron.actions.ActionPlaces;
import com.tyron.actions.AnAction;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.editor.Editor;
import javax.tools.Diagnostic;
public abstract class ExceptionsQuickFix extends AnAction {
public static final String ERROR_CODE =
"compiler.err.unreported.exception.need.to.catch.or" + ".throw";
@Override
public void update(@NonNull AnActionEvent event) {
event.getPresentation().setVisible(false);
if (!ActionPlaces.EDITOR.equals(event.getPlace())) {
return;
}
Diagnostic<?> diagnostic = event.getData(CommonDataKeys.DIAGNOSTIC);
if (diagnostic == null) {
return;
}
if (!ERROR_CODE.equals(diagnostic.getCode())) {
return;
}
TreePath currentPath = event.getData(CommonJavaContextKeys.CURRENT_PATH);
if (currentPath == null) {
return;
}
Editor editor = event.getData(CommonDataKeys.EDITOR);
if (editor == null) {
return;
}
event.getPresentation().setVisible(true);
}
@Override
public abstract void actionPerformed(@NonNull AnActionEvent e);
}
| 1,336 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.