Search in sources :

Example 6 with PackageID

use of org.ballerinalang.model.elements.PackageID in project ballerina by ballerina-lang.

the class ParserUtils method getAllPackages.

/**
 * Get All Native Packages.
 *
 * @return {@link Map} Package name, package functions and connectors
 */
public static Map<String, ModelPackage> getAllPackages() {
    final Map<String, ModelPackage> modelPackage = new HashMap<>();
    // TODO: remove once the packerina api for package listing is available
    final String[] packageNames = { "net.http", "net.http.authadaptor", "net.http.endpoints", "net.http.mock", "net.http.swagger", "net.uri", "mime", "net.websub", "net.websub.hub", "net.grpc", "auth", "auth.authz", "auth.authz.permissionstore", "auth.basic", "auth.jwtAuth", "auth.userstore", "auth.utils", "caching", "collections", "config", "data.sql", "file", "internal", "io", "jwt", "jwt.signature", "log", "math", "os", "reflect", "runtime", "security.crypto", "task", "time", "transactions.coordinator", "user", "util" };
    try {
        List<BLangPackage> builtInPackages = LSPackageLoader.getBuiltinPackages();
        for (BLangPackage bLangPackage : builtInPackages) {
            loadPackageMap(bLangPackage.packageID.getName().getValue(), bLangPackage, modelPackage);
        }
        CompilerContext context = CommonUtil.prepareTempCompilerContext();
        for (String packageName : packageNames) {
            PackageID packageID = new PackageID(new Name("ballerina"), new Name(packageName), new Name("0.0.0"));
            BLangPackage bLangPackage = LSPackageLoader.getPackageById(context, packageID);
            loadPackageMap(bLangPackage.packageID.getName().getValue(), bLangPackage, modelPackage);
        }
    } catch (Exception e) {
        // Above catch is to fail safe composer front end due to core errors.
        logger.warn("Error while loading packages");
    }
    return modelPackage;
}
Also used : BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) HashMap(java.util.HashMap) CompilerContext(org.wso2.ballerinalang.compiler.util.CompilerContext) ModelPackage(org.ballerinalang.composer.service.ballerina.parser.service.model.lang.ModelPackage) PackageID(org.ballerinalang.model.elements.PackageID) IOException(java.io.IOException) Name(org.wso2.ballerinalang.compiler.util.Name)

Example 7 with PackageID

use of org.ballerinalang.model.elements.PackageID in project ballerina by ballerina-lang.

the class PushUtils method pushPackages.

/**
 * Push/Uploads packages to the central repository.
 *
 * @param packageName   path of the package folder to be pushed
 * @param installToRepo if it should be pushed to central or home
 */
public static void pushPackages(String packageName, String installToRepo) {
    String accessToken = getAccessTokenOfCLI();
    Manifest manifest = readManifestConfigurations();
    if (manifest.getName() == null && manifest.getVersion() == null) {
        throw new BLangCompilerException("An org-name and package version is required when pushing. " + "This is not specified in Ballerina.toml inside the project");
    }
    String orgName = manifest.getName();
    String version = manifest.getVersion();
    PackageID packageID = new PackageID(new Name(orgName), new Name(packageName), new Name(version));
    Path prjDirPath = Paths.get(".").toAbsolutePath().normalize().resolve(ProjectDirConstants.DOT_BALLERINA_DIR_NAME);
    // Get package path from project directory path
    Path pkgPathFromPrjtDir = Paths.get(prjDirPath.toString(), "repo", Names.ANON_ORG.getValue(), packageName, Names.DEFAULT_VERSION.getValue(), packageName + ".zip");
    if (installToRepo == null) {
        if (accessToken == null) {
            // TODO: get bal home location dynamically
            throw new BLangCompilerException("Access token is missing in ~/ballerina_home/Settings.toml file.\n" + "Please visit https://central.ballerina.io/cli-token");
        }
        // Push package to central
        String resourcePath = resolvePkgPathInRemoteRepo(packageID);
        URI balxPath = URI.create(String.valueOf(PushUtils.class.getClassLoader().getResource("ballerina.push.balx")));
        String msg = orgName + "/" + packageName + ":" + version + " [project repo -> central]";
        ExecutorUtils.execute(balxPath, accessToken, resourcePath, pkgPathFromPrjtDir.toString(), msg);
    } else {
        if (!installToRepo.equals("home")) {
            throw new BLangCompilerException("Unknown repository provided to push the package");
        }
        Path balHomeDir = HomeRepoUtils.createAndGetHomeReposPath();
        Path targetDirectoryPath = Paths.get(balHomeDir.toString(), "repo", orgName, packageName, version, packageName + ".zip");
        if (Files.exists(targetDirectoryPath)) {
            throw new BLangCompilerException("Ballerina package exists in the home repository");
        } else {
            try {
                Files.createDirectories(targetDirectoryPath);
                Files.copy(pkgPathFromPrjtDir, targetDirectoryPath, StandardCopyOption.REPLACE_EXISTING);
                outStream.println(orgName + "/" + packageName + ":" + version + " [project repo -> home repo]");
            } catch (IOException e) {
                throw new BLangCompilerException("Error occurred when creating directories in the home repository");
            }
        }
    }
}
Also used : Path(java.nio.file.Path) BLangCompilerException(org.ballerinalang.compiler.BLangCompilerException) PackageID(org.ballerinalang.model.elements.PackageID) IOException(java.io.IOException) Manifest(org.ballerinalang.toml.model.Manifest) URI(java.net.URI) Name(org.wso2.ballerinalang.compiler.util.Name)

Example 8 with PackageID

use of org.ballerinalang.model.elements.PackageID in project ballerina by ballerina-lang.

the class PullCommand method execute.

@Override
public void execute() {
    if (helpFlag) {
        String commandUsageInfo = BLauncherCmd.getCommandUsageInfo(parentCmdParser, "pull");
        outStream.println(commandUsageInfo);
        return;
    }
    if (argList == null || argList.size() == 0) {
        throw new BLangCompilerException("no package given");
    }
    if (argList.size() > 1) {
        throw new BLangCompilerException("too many arguments");
    }
    // Enable remote debugging
    if (null != debugPort) {
        System.setProperty(SYSTEM_PROP_BAL_DEBUG, debugPort);
    }
    String resourceName = argList.get(0);
    String orgName;
    String packageName;
    String version;
    // Get org-name
    int orgNameIndex = resourceName.indexOf("/");
    if (orgNameIndex != -1) {
        orgName = resourceName.substring(0, orgNameIndex);
    } else {
        throw new BLangCompilerException("no package-name provided");
    }
    // Get package name
    int packageNameIndex = resourceName.indexOf(":");
    if (packageNameIndex != -1) {
        // version is provided
        packageName = resourceName.substring(orgNameIndex + 1, packageNameIndex);
        version = resourceName.substring(packageNameIndex + 1, resourceName.length());
    } else {
        packageName = resourceName.substring(orgNameIndex + 1, resourceName.length());
        version = "*";
    }
    URI baseURI = URI.create("https://staging.central.ballerina.io:9090/");
    Repo remoteRepo = new RemoteRepo(baseURI);
    PackageID packageID = new PackageID(new Name(orgName), new Name(packageName), new Name(version));
    Patten patten = remoteRepo.calculate(packageID);
    if (patten != Patten.NULL) {
        Converter converter = remoteRepo.getConverterInstance();
        patten.convertToSources(converter, packageID).collect(Collectors.toList());
    } else {
        outStream.println("couldn't find package " + patten);
    }
    Runtime.getRuntime().exit(0);
}
Also used : RemoteRepo(org.wso2.ballerinalang.compiler.packaging.repo.RemoteRepo) Repo(org.wso2.ballerinalang.compiler.packaging.repo.Repo) BLangCompilerException(org.ballerinalang.compiler.BLangCompilerException) Converter(org.wso2.ballerinalang.compiler.packaging.converters.Converter) RemoteRepo(org.wso2.ballerinalang.compiler.packaging.repo.RemoteRepo) PackageID(org.ballerinalang.model.elements.PackageID) Patten(org.wso2.ballerinalang.compiler.packaging.Patten) URI(java.net.URI) Name(org.wso2.ballerinalang.compiler.util.Name)

Example 9 with PackageID

use of org.ballerinalang.model.elements.PackageID in project ballerina by ballerina-lang.

the class BCompileUtil method compile.

/**
 * Compile and return the semantic errors.
 *
 * @param obj this is to find the original callers location.
 * @param sourceRoot  root path of the source packages
 * @param packageName name of the package to compile
 * @return Semantic errors
 */
public static CompileResult compile(Object obj, String sourceRoot, String packageName) {
    try {
        String effectiveSource;
        CodeSource codeSource = obj.getClass().getProtectionDomain().getCodeSource();
        URL location = codeSource.getLocation();
        URI locationUri = location.toURI();
        Path pathLocation = Paths.get(locationUri);
        String filePath = concatFileName(sourceRoot, pathLocation);
        Path rootPath = Paths.get(filePath);
        Path packagePath = Paths.get(packageName);
        if (Files.isDirectory(packagePath)) {
            String[] pkgParts = packageName.split("\\/");
            List<Name> pkgNameComps = Arrays.stream(pkgParts).map(part -> {
                if (part.equals("")) {
                    return Names.EMPTY;
                } else if (part.equals("_")) {
                    return Names.EMPTY;
                }
                return new Name(part);
            }).collect(Collectors.toList());
            // TODO: orgName is anon, fix it.
            PackageID pkgId = new PackageID(Names.ANON_ORG, pkgNameComps, Names.DEFAULT_VERSION);
            effectiveSource = pkgId.getName().getValue();
            return compile(rootPath.toString(), effectiveSource, CompilerPhase.CODE_GEN);
        } else {
            effectiveSource = packageName;
            return compile(rootPath.toString(), effectiveSource, CompilerPhase.CODE_GEN, new FileSystemProjectDirectory(rootPath));
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("error while running test: " + e.getMessage());
    }
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) CompilerUtils(org.wso2.ballerinalang.compiler.util.CompilerUtils) ProgramFile(org.ballerinalang.util.codegen.ProgramFile) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) Compiler(org.wso2.ballerinalang.compiler.Compiler) PackageInfo(org.ballerinalang.util.codegen.PackageInfo) PROJECT_DIR(org.ballerinalang.compiler.CompilerOptionName.PROJECT_DIR) SourceDirectory(org.wso2.ballerinalang.compiler.SourceDirectory) Diagnostic(org.ballerinalang.util.diagnostic.Diagnostic) Names(org.wso2.ballerinalang.compiler.util.Names) BStruct(org.ballerinalang.model.values.BStruct) StructInfo(org.ballerinalang.util.codegen.StructInfo) FileSystemProjectDirectory(org.wso2.ballerinalang.compiler.FileSystemProjectDirectory) URI(java.net.URI) PRESERVE_WHITESPACE(org.ballerinalang.compiler.CompilerOptionName.PRESERVE_WHITESPACE) Path(java.nio.file.Path) LauncherUtils(org.ballerinalang.launcher.LauncherUtils) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) DiagnosticListener(org.ballerinalang.util.diagnostic.DiagnosticListener) Files(java.nio.file.Files) CompilerPhase(org.ballerinalang.compiler.CompilerPhase) PackageID(org.ballerinalang.model.elements.PackageID) COMPILER_PHASE(org.ballerinalang.compiler.CompilerOptionName.COMPILER_PHASE) IOException(java.io.IOException) BStructType(org.ballerinalang.model.types.BStructType) CompiledBinaryFile(org.wso2.ballerinalang.programfile.CompiledBinaryFile) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) Name(org.wso2.ballerinalang.compiler.util.Name) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) Paths(java.nio.file.Paths) BufferedReader(java.io.BufferedReader) CodeSource(java.security.CodeSource) CompilerOptions(org.wso2.ballerinalang.compiler.util.CompilerOptions) CompilerContext(org.wso2.ballerinalang.compiler.util.CompilerContext) InputStream(java.io.InputStream) FileSystemProjectDirectory(org.wso2.ballerinalang.compiler.FileSystemProjectDirectory) URISyntaxException(java.net.URISyntaxException) CodeSource(java.security.CodeSource) URI(java.net.URI) URL(java.net.URL) Name(org.wso2.ballerinalang.compiler.util.Name) PackageID(org.ballerinalang.model.elements.PackageID)

Example 10 with PackageID

use of org.ballerinalang.model.elements.PackageID in project ballerina by ballerina-lang.

the class GeneralFSPackageRepository method listPackages.

@Override
public Set<PackageID> listPackages(int maxDepth) {
    if (maxDepth <= 0) {
        throw new IllegalArgumentException("maxDepth must be greater than zero");
    }
    if (!Files.isDirectory(this.basePath)) {
        return Collections.emptySet();
    }
    Set<PackageID> result = new LinkedHashSet<>();
    int baseNameCount = this.basePath.getNameCount();
    String separator = this.basePath.getFileSystem().getSeparator();
    try {
        Files.walkFileTree(this.basePath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (Files.isHidden(dir)) {
                    return FileVisitResult.SKIP_SUBTREE;
                }
                List<Name> nameComps = new ArrayList<>();
                if (Files.list(dir).filter(f -> isBALFile(f)).count() > 0) {
                    int dirNameCount = dir.getNameCount();
                    if (dirNameCount > baseNameCount) {
                        dir.subpath(baseNameCount, dirNameCount).forEach(f -> nameComps.add(new Name(sanitize(f.getFileName().toString(), separator))));
                        result.add(new PackageID(Names.ANON_ORG, nameComps, Names.DEFAULT_VERSION));
                    }
                }
                if ((dir.getNameCount() + 1) - baseNameCount > maxDepth) {
                    return FileVisitResult.SKIP_SUBTREE;
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new RuntimeException("Error in listing packages: " + e.getMessage(), e);
    }
    return result;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Path(java.nio.file.Path) Files(java.nio.file.Files) PackageID(org.ballerinalang.model.elements.PackageID) Set(java.util.Set) PackageSource(org.ballerinalang.repository.PackageSource) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) Name(org.wso2.ballerinalang.compiler.util.Name) ArrayList(java.util.ArrayList) PackageSourceEntry(org.ballerinalang.repository.PackageSourceEntry) FileVisitResult(java.nio.file.FileVisitResult) LinkOption(java.nio.file.LinkOption) List(java.util.List) PackageEntity(org.ballerinalang.repository.PackageEntity) PackageRepository(org.ballerinalang.repository.PackageRepository) Names(org.wso2.ballerinalang.compiler.util.Names) RepoHierarchy(org.wso2.ballerinalang.compiler.packaging.RepoHierarchy) Path(java.nio.file.Path) Collections(java.util.Collections) LinkedHashSet(java.util.LinkedHashSet) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) Name(org.wso2.ballerinalang.compiler.util.Name) PackageID(org.ballerinalang.model.elements.PackageID) ArrayList(java.util.ArrayList) List(java.util.List) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

PackageID (org.ballerinalang.model.elements.PackageID)23 Name (org.wso2.ballerinalang.compiler.util.Name)10 ArrayList (java.util.ArrayList)9 Test (org.testng.annotations.Test)8 Path (java.nio.file.Path)7 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)7 CompilerContext (org.wso2.ballerinalang.compiler.util.CompilerContext)7 List (java.util.List)6 Patten (org.wso2.ballerinalang.compiler.packaging.Patten)6 RepoHierarchy (org.wso2.ballerinalang.compiler.packaging.RepoHierarchy)6 IOException (java.io.IOException)5 URI (java.net.URI)5 Collectors (java.util.stream.Collectors)5 BLangCompilerException (org.ballerinalang.compiler.BLangCompilerException)5 Resolution (org.wso2.ballerinalang.compiler.packaging.Resolution)5 Names (org.wso2.ballerinalang.compiler.util.Names)5 Arrays (java.util.Arrays)4 Collections (java.util.Collections)4 Set (java.util.Set)4 CacheRepo (org.wso2.ballerinalang.compiler.packaging.repo.CacheRepo)4