Search in sources :

Example 6 with StarlarkMethod

use of net.starlark.java.annot.StarlarkMethod in project copybara by google.

the class ModuleLoader method processStarlarkMethod.

private DocFunction processStarlarkMethod(Method method, StarlarkMethod annotation, @Nullable String prefix) {
    Type[] genericParameterTypes = method.getGenericParameterTypes();
    Param[] starlarkParams = annotation.parameters();
    if (genericParameterTypes.length < starlarkParams.length) {
        throw new IllegalStateException(String.format("Missing java parameters for: %s\n" + "%s\n" + "%s", method, Arrays.toString(genericParameterTypes), Arrays.toString(starlarkParams)));
    }
    ImmutableList.Builder<DocParam> params = ImmutableList.builder();
    Map<String, DocDefault> docDefaultsMap = stream(method.getAnnotationsByType(DocDefault.class)).collect(Collectors.toMap(DocDefault::field, identity(), (f, v) -> v));
    for (int i = 0; i < starlarkParams.length; i++) {
        Type parameterType = genericParameterTypes[i];
        Param starlarkParam = starlarkParams[i];
        // Compute the list of names of allowed types (e.g. string or bool or NoneType).
        List<String> allowedTypeNames = new ArrayList<>();
        if (starlarkParam.allowedTypes().length > 0) {
            for (ParamType param : starlarkParam.allowedTypes()) {
                allowedTypeNames.add(skylarkTypeName(param.type()) + (param.generic1() != Object.class ? " of " + skylarkTypeName(param.generic1()) : ""));
            }
        } else {
            // Otherwise use the type of the parameter variable itself.
            allowedTypeNames.add(skylarkTypeName(parameterType));
        }
        DocDefault fieldInfo = docDefaultsMap.get(starlarkParam.name());
        if (fieldInfo != null && fieldInfo.allowedTypes().length > 0) {
            allowedTypeNames = Arrays.asList(fieldInfo.allowedTypes());
        }
        params.add(new DocParam(starlarkParam.name(), fieldInfo != null ? fieldInfo.value() : emptyToNull(starlarkParam.defaultValue()), allowedTypeNames, starlarkParam.doc()));
    }
    String returnType = method.getGenericReturnType().equals(NoneType.class) || method.getGenericReturnType().equals(void.class) ? null : skylarkTypeName(method.getGenericReturnType());
    return new DocFunction(prefix != null ? prefix + "." + annotation.name() : annotation.name(), annotation.doc(), returnType, params.build(), generateFlagsInfo(method), stream(method.getAnnotationsByType(Example.class)).map(DocExample::new).collect(toImmutableList()));
}
Also used : UsesFlags(com.google.copybara.doc.annotations.UsesFlags) DocExample(com.google.copybara.doc.DocBase.DocExample) Arrays(java.util.Arrays) DocFlag(com.google.copybara.doc.DocBase.DocFlag) HtmlEscapers(com.google.common.html.HtmlEscapers) DurationConverter(com.google.copybara.jcommander.DurationConverter) DocDefault(com.google.copybara.doc.annotations.DocDefault) CharStreams(com.google.common.io.CharStreams) Map(java.util.Map) ZipFile(java.util.zip.ZipFile) Splitter(com.google.common.base.Splitter) Method(java.lang.reflect.Method) ZipEntry(java.util.zip.ZipEntry) Param(net.starlark.java.annot.Param) DocModule(com.google.copybara.doc.DocBase.DocModule) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Collection(java.util.Collection) Collectors(java.util.stream.Collectors) List(java.util.List) StarlarkMethod(net.starlark.java.annot.StarlarkMethod) Type(java.lang.reflect.Type) NoneType(net.starlark.java.eval.NoneType) Function.identity(java.util.function.Function.identity) Pattern(com.google.re2j.Pattern) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) DocFunction(com.google.copybara.doc.DocBase.DocFunction) DocSignaturePrefix(com.google.copybara.doc.annotations.DocSignaturePrefix) DocField(com.google.copybara.doc.DocBase.DocField) Arrays.stream(java.util.Arrays.stream) SortedMap(java.util.SortedMap) Joiner(com.google.common.base.Joiner) AnnotatedElement(java.lang.reflect.AnnotatedElement) Library(com.google.copybara.doc.annotations.Library) Matcher(com.google.re2j.Matcher) Parameter(com.beust.jcommander.Parameter) WildcardType(java.lang.reflect.WildcardType) StarlarkBuiltin(net.starlark.java.annot.StarlarkBuiltin) ArrayList(java.util.ArrayList) Example(com.google.copybara.doc.annotations.Example) ImmutableList(com.google.common.collect.ImmutableList) DocParam(com.google.copybara.doc.DocBase.DocParam) ParamType(net.starlark.java.annot.ParamType) Starlark(net.starlark.java.eval.Starlark) Nullable(javax.annotation.Nullable) UTF_8(java.nio.charset.StandardCharsets.UTF_8) IOException(java.io.IOException) Field(java.lang.reflect.Field) InputStreamReader(java.io.InputStreamReader) Strings.emptyToNull(com.google.common.base.Strings.emptyToNull) ParameterizedType(java.lang.reflect.ParameterizedType) TreeMap(java.util.TreeMap) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) DocDefault(com.google.copybara.doc.annotations.DocDefault) ArrayList(java.util.ArrayList) DocFunction(com.google.copybara.doc.DocBase.DocFunction) ParamType(net.starlark.java.annot.ParamType) Type(java.lang.reflect.Type) NoneType(net.starlark.java.eval.NoneType) WildcardType(java.lang.reflect.WildcardType) ParamType(net.starlark.java.annot.ParamType) ParameterizedType(java.lang.reflect.ParameterizedType) DocExample(com.google.copybara.doc.DocBase.DocExample) Param(net.starlark.java.annot.Param) DocParam(com.google.copybara.doc.DocBase.DocParam) DocParam(com.google.copybara.doc.DocBase.DocParam)

Example 7 with StarlarkMethod

use of net.starlark.java.annot.StarlarkMethod in project copybara by google.

the class FormatModule method buildifier.

@StarlarkMethod(name = "buildifier", doc = "Formats the BUILD files using buildifier.", parameters = { @Param(name = "paths", allowedTypes = { @ParamType(type = Glob.class), @ParamType(type = NoneType.class) }, doc = "Paths of the files to format relative to the workdir.", defaultValue = "None", named = true), @Param(name = "type", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, doc = "The type of the files. Can be 'auto', 'bzl', 'build' or 'workspace'. Note that" + " this is not recommended to be set and might break in the future. The" + " default is 'auto'. This mode formats as BUILD files \"BUILD\"," + " \"BUILD.bazel\", \"WORKSPACE\" and \"WORKSPACE.bazel\" files. The rest as" + " bzl files. Prefer to use those names for BUILD files instead of setting" + " this flag.", defaultValue = "'auto'", named = true), @Param(name = "lint", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, doc = "If buildifier --lint should be used. This fixes several common issues. Note that" + " this transformation is difficult to revert. For example if it removes a" + " load statement because is not used after removing a rule, then the reverse" + " workflow needs to add back the load statement (core.replace or similar). " + " Possible values: `OFF`, `FIX`. Default is `OFF`", defaultValue = "None", named = true), @Param(name = "lint_warnings", allowedTypes = { @ParamType(type = Sequence.class, generic1 = String.class) }, defaultValue = "[]", doc = "Warnings used in the lint mode. Default is buildifier default`", named = true) })
@DocDefault(field = "lint", value = "\"OFF\"")
@UsesFlags(BuildifierOptions.class)
@Example(title = "Default usage", before = "The default parameters formats all BUILD and bzl files in the checkout directory:", code = "format.buildifier()")
@Example(title = "Enable lint", before = "Enable lint for buildifier", code = "format.buildifier(lint = \"FIX\")")
@Example(title = "Using globs", before = "Globs can be used to match only certain files:", code = "format.buildifier(\n" + "    paths = glob([\"foo/BUILD\", \"foo/**/BUILD\"], exclude = [\"foo/bar/BUILD\"])" + "\n)", after = "Formats all the BUILD files inside `foo` except for `foo/bar/BUILD`")
@DocDefault(field = "paths", value = "glob([\"**.bzl\", \"**/BUILD\", \"BUILD\"])")
public Transformation buildifier(// <String>
Object paths, // <String>
Object type, // <String>
Object lint, // <String>
Sequence<?> warnings) throws EvalException {
    String typeStr = convertFromNoneable(type, null);
    if (typeStr != null) {
        check(BUILDIFIER_TYPE_VALUES.contains(typeStr), "Non-valid type: %s. Valid types: %s", typeStr, BUILDIFIER_TYPE_VALUES);
    }
    LintMode lintMode = stringToEnum("lint", convertFromNoneable(lint, "OFF"), LintMode.class);
    check(lintMode != LintMode.OFF || warnings.isEmpty(), "Warnings can only be used when lint is set to FIX");
    return new BuildifierFormat(buildifierOptions, generalOptions, convertFromNoneable(paths, DEFAULT_BUILDIFIER_PATHS), lintMode, ImmutableList.copyOf(Sequence.cast(warnings, String.class, "lint_warnings")), typeStr);
}
Also used : LintMode(com.google.copybara.format.BuildifierFormat.LintMode) StarlarkMethod(net.starlark.java.annot.StarlarkMethod) UsesFlags(com.google.copybara.doc.annotations.UsesFlags) DocDefault(com.google.copybara.doc.annotations.DocDefault) Example(com.google.copybara.doc.annotations.Example)

Example 8 with StarlarkMethod

use of net.starlark.java.annot.StarlarkMethod in project copybara by google.

the class GitHubEndPoint method getPullRequests.

@StarlarkMethod(name = "get_pull_requests", doc = "Get Pull Requests for a repo", parameters = { @Param(name = "head_prefix", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "Only return PRs wher the branch name has head_prefix", defaultValue = "None"), @Param(name = "base_prefix", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "Only return PRs where the destination branch name has base_prefix", defaultValue = "None"), @Param(name = "state", doc = "State of the Pull Request. Can be `\"OPEN\"`, `\"CLOSED\"` or `\"ALL\"`", defaultValue = "\"OPEN\"", named = true), @Param(name = "sort", doc = "Sort filter for retrieving the Pull Requests. Can be `\"CREATED\"`," + " `\"UPDATED\"` or `\"POPULARITY\"`", named = true, defaultValue = "\"CREATED\""), @Param(name = "direction", doc = "Direction of the filter. Can be `\"ASC\"` or `\"DESC\"`", defaultValue = "\"ASC\"", named = true) }, allowReturnNones = true)
@Nullable
public ImmutableList<PullRequest> getPullRequests(Object headPrefixParam, Object basePrefixParam, String state, String sort, String direction) throws EvalException, RepoException {
    try {
        String project = ghHost.getProjectNameFromUrl(url);
        PullRequestListParams request = PullRequestListParams.DEFAULT;
        String headPrefix = convertFromNoneable(headPrefixParam, null);
        String basePrefix = convertFromNoneable(basePrefixParam, null);
        if (!Strings.isNullOrEmpty(headPrefix)) {
            checkCondition(SAFE_BRANCH_NAME_PREFIX.matches(headPrefix), "'%s' is not a valid head_prefix (%s is used for validation)", headPrefix, SAFE_BRANCH_NAME_PREFIX.pattern());
            request = request.withHead(headPrefix);
        }
        if (!Strings.isNullOrEmpty(basePrefix)) {
            checkCondition(SAFE_BRANCH_NAME_PREFIX.matches(basePrefix), "'%s' is not a valid base_prefix (%s is used for validation)", basePrefix, SAFE_BRANCH_NAME_PREFIX.pattern());
            request = request.withHead(basePrefix);
        }
        return apiSupplier.load(console).getPullRequests(project, request.withState(stringToEnum("state", state, StateFilter.class)).withDirection(stringToEnum("direction", direction, DirectionFilter.class)).withSort(stringToEnum("sort", sort, SortFilter.class)));
    } catch (GitHubApiException e) {
        return returnNullOnNotFound(e);
    } catch (ValidationException | RuntimeException e) {
        throw Starlark.errorf("Error calling get_pull_requests: %s", e.getMessage());
    }
}
Also used : DirectionFilter(com.google.copybara.git.github.api.GitHubApi.PullRequestListParams.DirectionFilter) ValidationException(com.google.copybara.exception.ValidationException) GitHubApiException(com.google.copybara.git.github.api.GitHubApiException) PullRequestListParams(com.google.copybara.git.github.api.GitHubApi.PullRequestListParams) StarlarkMethod(net.starlark.java.annot.StarlarkMethod) Nullable(javax.annotation.Nullable)

Example 9 with StarlarkMethod

use of net.starlark.java.annot.StarlarkMethod in project copybara by google.

the class GitHubEndPoint method updateReference.

@StarlarkMethod(name = "update_reference", doc = "Update a reference to point to a new commit. Returns the info of the reference.", parameters = { @Param(name = "ref", named = true, doc = "The name of the reference."), @Param(name = "sha", doc = "The id for the commit" + " status.", named = true), @Param(name = "force", named = true, doc = "Indicates whether to force the update or to make sure the update is a" + " fast-forward update. Leaving this out or setting it to false will make" + " sure you're not overwriting work. Default: false") })
public Ref updateReference(String sha, String ref, boolean force) throws EvalException, RepoException {
    try {
        checkCondition(GitRevision.COMPLETE_SHA1_PATTERN.matcher(sha).matches(), "Not a valid complete SHA-1: %s", sha);
        checkCondition(!Strings.isNullOrEmpty(ref), "ref cannot be empty");
        if (!ref.startsWith("refs/")) {
            // TODO(malcon): Remove this functionality and use a check once library migrated.
            console.warnFmt("Non-complete ref passed to update_reference '%s'. Assuming refs/heads/%s", ref, ref);
            ref = "refs/heads/" + ref;
        }
        String project = ghHost.getProjectNameFromUrl(url);
        return apiSupplier.load(console).updateReference(project, ref, new UpdateReferenceRequest(sha, force));
    } catch (ValidationException | RuntimeException e) {
        throw Starlark.errorf("Error calling update_reference: %s", e.getMessage());
    }
}
Also used : UpdateReferenceRequest(com.google.copybara.git.github.api.UpdateReferenceRequest) ValidationException(com.google.copybara.exception.ValidationException) StarlarkMethod(net.starlark.java.annot.StarlarkMethod)

Example 10 with StarlarkMethod

use of net.starlark.java.annot.StarlarkMethod in project copybara by google.

the class GitMirrorContext method merge.

@StarlarkMethod(name = "merge", doc = "Merge one or more commits into a local branch.", parameters = { @Param(name = "branch", named = true), @Param(name = "commits", allowedTypes = { @ParamType(type = Sequence.class, generic1 = String.class) }, named = true), @Param(name = "msg", named = true, defaultValue = "None") })
public MergeResult merge(String branch, Sequence<?> commits, Object msg) throws RepoException, ValidationException, EvalException, IOException {
    ValidationException.checkCondition(!commits.isEmpty(), "At least one commit should be passed to merge");
    GitRepository withWorktree = this.repo.withWorkTree(dirFactory.newTempDir("mirror"));
    try {
        withWorktree.forceCheckout(branch);
    } catch (RepoException e) {
        throw new ValidationException("Cannot merge commits " + commits + " into branch " + branch + " because of failure during merge checkout", e);
    }
    String strMsg = SkylarkUtil.convertFromNoneable(msg, null);
    // Clean everything before the merge
    withWorktree.simpleCommand("reset", "--hard");
    withWorktree.forceClean();
    List<String> cmd = Lists.newArrayList("merge");
    if (strMsg != null) {
        cmd.add("-m");
        cmd.add(strMsg);
    }
    cmd.addAll(SkylarkUtil.convertStringList(commits, "commits"));
    try {
        withWorktree.simpleCommand(cmd);
    } catch (RepoException e) {
        logger.atWarning().withCause(e).log("Error running merge in action %s for branch %s and commits %s", getActionName(), branch, commits);
        return MergeResult.error(e.getMessage());
    }
    return MergeResult.success();
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) RepoException(com.google.copybara.exception.RepoException) StarlarkMethod(net.starlark.java.annot.StarlarkMethod)

Aggregations

StarlarkMethod (net.starlark.java.annot.StarlarkMethod)37 UsesFlags (com.google.copybara.doc.annotations.UsesFlags)17 DocDefault (com.google.copybara.doc.annotations.DocDefault)9 Checker (com.google.copybara.checks.Checker)8 Example (com.google.copybara.doc.annotations.Example)8 GeneralOptions (com.google.copybara.GeneralOptions)7 ValidationException (com.google.copybara.exception.ValidationException)7 Pattern (com.google.re2j.Pattern)6 SubmoduleStrategy (com.google.copybara.git.GitOrigin.SubmoduleStrategy)4 PatchTransformation (com.google.copybara.transform.patch.PatchTransformation)4 ImmutableList (com.google.common.collect.ImmutableList)3 LabelsAwareModule (com.google.copybara.config.LabelsAwareModule)3 SkylarkTransformation (com.google.copybara.transform.SkylarkTransformation)3 Transformations.toTransformation (com.google.copybara.transform.Transformations.toTransformation)3 IOException (java.io.IOException)3 Module (net.starlark.java.eval.Module)3 Action (com.google.copybara.action.Action)2 StarlarkAction (com.google.copybara.action.StarlarkAction)2 RepoException (com.google.copybara.exception.RepoException)2 FolderModule (com.google.copybara.folder.FolderModule)2