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()));
}
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);
}
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());
}
}
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());
}
}
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();
}
Aggregations