Search in sources :

Example 26 with StarlarkMethod

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

the class GerritEndpoint method deleteVote.

@StarlarkMethod(name = "delete_vote", doc = "Delete a label vote from an account owner on a Gerrit change.\n", parameters = { @Param(name = "change_id", named = true, doc = "The Gerrit change id."), @Param(name = "account_id", named = true, doc = "The account owner who votes on label_id. Use 'me' or 'self' " + "if the account owner makes this api call"), @Param(name = "label_id", named = true, doc = "The name of the label.") })
public void deleteVote(String changeId, String accountId, String labelId) throws EvalException {
    try {
        GerritApi gerritApi = apiSupplier.load(console);
        gerritApi.deleteVote(changeId, accountId, labelId, new DeleteVoteInput(NotifyType.NONE));
    } catch (RepoException | ValidationException | RuntimeException e) {
        throw new EvalException("Error calling delete_vote: " + e.getMessage(), e);
    }
}
Also used : DeleteVoteInput(com.google.copybara.git.gerritapi.DeleteVoteInput) ValidationException(com.google.copybara.exception.ValidationException) RepoException(com.google.copybara.exception.RepoException) EvalException(net.starlark.java.eval.EvalException) GerritApi(com.google.copybara.git.gerritapi.GerritApi) StarlarkMethod(net.starlark.java.annot.StarlarkMethod)

Example 27 with StarlarkMethod

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

the class GitHubEndPoint method createStatus.

@StarlarkMethod(name = "create_status", doc = "Create or update a status for a commit. Returns the status created.", parameters = { @Param(name = "sha", named = true, doc = "The SHA-1 for which we want to create or update the status"), @Param(name = "state", named = true, doc = "The state of the commit status: 'success', 'error', 'pending' or 'failure'"), @Param(name = "context", doc = "The context for the commit status. Use a value like 'copybara/import_successful'" + " or similar", named = true), @Param(name = "description", named = true, doc = "Description about what happened"), @Param(name = "target_url", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "Url with expanded information about the event", defaultValue = "None") })
public Status createStatus(String sha, String state, String context, String description, Object targetUrl) throws EvalException, RepoException, ValidationException {
    try {
        checkCondition(State.VALID_VALUES.contains(state), "Invalid value for state. Valid values: %s", State.VALID_VALUES);
        checkCondition(GitRevision.COMPLETE_SHA1_PATTERN.matcher(sha).matches(), "Not a valid complete SHA-1: %s", sha);
        checkCondition(!Strings.isNullOrEmpty(description), "description cannot be empty");
        checkCondition(!Strings.isNullOrEmpty(context), "context cannot be empty");
        String project = ghHost.getProjectNameFromUrl(url);
        return apiSupplier.load(console).createStatus(project, sha, new CreateStatusRequest(State.valueOf(state.toUpperCase()), convertFromNoneable(targetUrl, null), description, context));
    } catch (GitHubApiException gae) {
        if (gae.getResponseCode() == ResponseCode.UNPROCESSABLE_ENTITY) {
            throw new ValidationException("GitHub was unable to process the request " + gae.getError(), gae);
        }
        throw gae;
    } catch (ValidationException | RuntimeException e) {
        throw Starlark.errorf("Error calling create_status: %s", e.getMessage());
    }
}
Also used : CreateStatusRequest(com.google.copybara.git.github.api.CreateStatusRequest) ValidationException(com.google.copybara.exception.ValidationException) GitHubApiException(com.google.copybara.git.github.api.GitHubApiException) StarlarkMethod(net.starlark.java.annot.StarlarkMethod)

Example 28 with StarlarkMethod

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

the class GitModule method githubOrigin.

@SuppressWarnings("unused")
@StarlarkMethod(name = "github_origin", doc = "Defines a Git origin for a Github repository. This origin should be used for public" + " branches. Use " + GITHUB_PR_ORIGIN_NAME + " for importing Pull Requests.", parameters = { @Param(name = "url", named = true, doc = "Indicates the URL of the git repository"), @Param(name = "ref", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, defaultValue = "None", named = true, doc = "Represents the default reference that will be used for reading the revision " + "from the git repository. For example: 'master'"), @Param(name = "submodules", defaultValue = "'NO'", named = true, doc = "Download submodules. Valid values: NO, YES, RECURSIVE."), @Param(name = "first_parent", defaultValue = "True", named = true, doc = "If true, it only uses the first parent when looking for changes. Note that" + " when disabled in ITERATIVE mode, it will try to do a migration for each" + " change of the merged branch.", positional = false), @Param(name = "partial_fetch", defaultValue = "False", named = true, positional = false, doc = "If true, partially fetch git repository by only fetching affected files."), @Param(name = PATCH_FIELD, allowedTypes = { @ParamType(type = Transformation.class), @ParamType(type = NoneType.class) }, defaultValue = "None", named = true, positional = false, doc = PATCH_FIELD_DESC), @Param(name = "describe_version", allowedTypes = { @ParamType(type = Boolean.class), @ParamType(type = NoneType.class) }, defaultValue = "None", named = true, positional = false, doc = DESCRIBE_VERSION_FIELD_DOC), @Param(name = "version_selector", allowedTypes = { @ParamType(type = VersionSelector.class), @ParamType(type = NoneType.class) }, defaultValue = "None", named = true, positional = false, doc = "Select a custom version (tag)to migrate" + " instead of 'ref'"), @Param(name = "primary_branch_migration", allowedTypes = { @ParamType(type = Boolean.class) }, defaultValue = "False", named = true, positional = false, doc = "When enabled, copybara will ignore the 'ref' param if it is 'master' or 'main'" + " and instead try to establish the default git branch. If this fails, it will " + "fall back to the 'ref' param.\n" + "This is intended to help migrating to the new standard of using 'main' without " + "breaking users relying on the legacy default.") }, useStarlarkThread = true)
public GitOrigin githubOrigin(String url, Object ref, String submodules, Boolean firstParent, Boolean partialFetch, Object patch, Object describeVersion, Object versionSelector, Boolean primaryBranchMigration, StarlarkThread thread) throws EvalException {
    check(GITHUB_COM.isGitHubUrl(checkNotEmpty(url, "url")), "Invalid Github URL: %s", url);
    if (versionSelector != Starlark.NONE) {
        check(ref == Starlark.NONE, "Cannot use ref field and version_selector. Version selector will decide the ref" + " to migrate");
    }
    PatchTransformation patchTransformation = maybeGetPatchTransformation(patch);
    // TODO(copybara-team): See if we want to support includeBranchCommitLogs for GitHub repos.
    return GitOrigin.newGitOrigin(options, fixHttp(url, thread.getCallerLocation()), SkylarkUtil.convertOptionalString(ref), GitRepoType.GITHUB, stringToEnum("submodules", submodules, GitOrigin.SubmoduleStrategy.class), /*includeBranchCommitLogs=*/
    false, firstParent, partialFetch, primaryBranchMigration, patchTransformation, convertDescribeVersion(describeVersion), convertFromNoneable(versionSelector, null), mainConfigFile.path(), workflowName);
}
Also used : PatchTransformation(com.google.copybara.transform.patch.PatchTransformation) SubmoduleStrategy(com.google.copybara.git.GitOrigin.SubmoduleStrategy) StarlarkMethod(net.starlark.java.annot.StarlarkMethod)

Example 29 with StarlarkMethod

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

the class GitModule method gitHubDestination.

@SuppressWarnings("unused")
@StarlarkMethod(name = "github_destination", doc = "Creates a commit in a GitHub repository branch (for example master). For creating Pull" + "Request use git.github_pr_destination.", parameters = { @Param(name = "url", named = true, doc = "Indicates the URL to push to as well as the URL from which to get the parent " + "commit"), @Param(name = "push", named = true, doc = "Reference to use for pushing the change, for example 'main'.", defaultValue = "'master'"), @Param(name = "fetch", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "Indicates the ref from which to get the parent commit. Defaults to push value" + " if None", defaultValue = "None"), @Param(name = "pr_branch_to_update", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "A template string that refers to a pull request branch in the same repository" + " will be updated to current commit of this push branch only if" + " pr_branch_to_update exists. The reason behind this field is that" + " presubmiting changes creates and leaves a pull request open. By using" + " this, we can automerge/close this type of pull requests. As a result," + " users will see this pr_branch_to_update as merged to this push branch." + " Usage: Users can use a string or a string with a label. For instance" + " ${label}_pr_branch_name. And the value of label must be in changes' label" + " list. Otherwise, nothing will happen.", defaultValue = "None"), @Param(name = "partial_fetch", defaultValue = "False", named = true, doc = "This is an experimental feature that only works for certain origin globs."), @Param(name = "delete_pr_branch", allowedTypes = { @ParamType(type = Boolean.class), @ParamType(type = NoneType.class) }, named = true, doc = "When `pr_branch_to_update` is enabled, it will delete the branch reference" + " after the push to the branch and main branch (i.e master) happens. This" + " allows to cleanup temporary branches created for testing.", defaultValue = "None"), @Param(name = "integrates", named = true, allowedTypes = { @ParamType(type = Sequence.class, generic1 = GitIntegrateChanges.class), @ParamType(type = NoneType.class) }, defaultValue = "None", doc = "Integrate changes from a url present in the migrated change" + " label. Defaults to a semi-fake merge if COPYBARA_INTEGRATE_REVIEW label is" + " present in the message", positional = false), @Param(name = "api_checker", allowedTypes = { @ParamType(type = Checker.class), @ParamType(type = NoneType.class) }, defaultValue = "None", doc = "A checker for the Gerrit API endpoint provided for after_migration hooks. " + "This field is not required if the workflow hooks don't use the " + "origin/destination endpoints.", named = true, positional = false), @Param(name = "primary_branch_migration", allowedTypes = { @ParamType(type = Boolean.class) }, defaultValue = "False", named = true, positional = false, doc = "When enabled, copybara will ignore the 'push' and 'fetch' params if either is" + " 'master' or 'main' and instead try to establish the default git branch. If" + " this fails, it will fall back to the param's declared value.\n" + "This is intended to help migrating to the new standard of using 'main'" + " without breaking users relying on the legacy default."), @Param(name = "tag_name", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, positional = false, doc = "A template string that specifies to a tag name. If the tag already exists, " + "copybara will only overwrite it if the --git-tag-overwrite flag is set." + "\nNote that tag creation is " + "best-effort and the migration will succeed even if the tag cannot be " + "created. " + "Usage: Users can use a string or a string with a label. " + "For instance ${label}_tag_name. And the value of label must be " + "in changes' label list. Otherwise, tag won't be created.", defaultValue = "None"), @Param(name = "tag_msg", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, positional = false, doc = "A template string that refers to the commit msg for a tag. If set, copybara will" + "create an annotated tag with this custom message\n" + "Usage: Labels in the string will be resolved. E.g. .${label}_message." + "By default, the tag will be created with the labeled commit's message.", defaultValue = "None"), @Param(name = "checker", allowedTypes = { @ParamType(type = Checker.class), @ParamType(type = NoneType.class) }, defaultValue = "None", doc = "A checker that validates the commit files & message. If `api_checker` is not" + " set, it will also be used for checking API calls. If only `api_checker`" + "is used, that checker will only apply to API calls.", named = true, positional = false) }, useStarlarkThread = true)
@UsesFlags(GitDestinationOptions.class)
// Used to detect in the future users that don't set it and change the default
@DocDefault(field = "delete_pr_branch", value = "False")
public GitDestination gitHubDestination(String url, String push, Object fetch, Object prBranchToUpdate, Boolean partialFetch, Object deletePrBranchParam, Object integrates, Object apiChecker, Boolean primaryBranchMigration, Object tagName, Object tagMsg, Object checker, StarlarkThread thread) throws EvalException {
    GitDestinationOptions destinationOptions = options.get(GitDestinationOptions.class);
    String resolvedPush = checkNotEmpty(firstNotNull(destinationOptions.push, push), "push");
    GeneralOptions generalOptions = options.get(GeneralOptions.class);
    String repoUrl = fixHttp(checkNotEmpty(firstNotNull(destinationOptions.url, url), "url"), thread.getCallerLocation());
    String branchToUpdate = convertFromNoneable(prBranchToUpdate, null);
    Boolean deletePrBranch = convertFromNoneable(deletePrBranchParam, null);
    check(branchToUpdate != null || deletePrBranch == null, "'delete_pr_branch' can only be set if 'pr_branch_to_update' is used");
    GitHubOptions gitHubOptions = options.get(GitHubOptions.class);
    WorkflowOptions workflowOptions = options.get(WorkflowOptions.class);
    String effectivePrBranchToUpdate = branchToUpdate;
    if (options.get(WorkflowOptions.class).isInitHistory()) {
        generalOptions.console().infoFmt("Ignoring field 'pr_branch_to_update' as '--init-history' is set.");
        effectivePrBranchToUpdate = null;
    }
    // First flag has priority, then field, and then (for now) we set it to false.
    // TODO(malcon): Once this is stable the default will be 'branchToUpdate != null'
    boolean effectiveDeletePrBranch = gitHubOptions.gitHubDeletePrBranch != null ? gitHubOptions.gitHubDeletePrBranch : deletePrBranch != null ? deletePrBranch : false;
    Checker apiCheckerObj = convertFromNoneable(apiChecker, null);
    Checker checkerObj = convertFromNoneable(checker, null);
    return new GitDestination(repoUrl, checkNotEmpty(firstNotNull(destinationOptions.fetch, convertFromNoneable(fetch, null), resolvedPush), "fetch"), resolvedPush, partialFetch, primaryBranchMigration, convertFromNoneable(tagName, null), convertFromNoneable(tagMsg, null), destinationOptions, options.get(GitOptions.class), generalOptions, new GitHubWriteHook(generalOptions, repoUrl, gitHubOptions, effectivePrBranchToUpdate, effectiveDeletePrBranch, getGeneralConsole(), apiCheckerObj != null ? apiCheckerObj : checkerObj, GITHUB_COM), Starlark.isNullOrNone(integrates) ? defaultGitIntegrate : Sequence.cast(integrates, GitIntegrateChanges.class, "integrates"), checkerObj);
}
Also used : GeneralOptions(com.google.copybara.GeneralOptions) Checker(com.google.copybara.checks.Checker) WorkflowOptions(com.google.copybara.WorkflowOptions) StarlarkMethod(net.starlark.java.annot.StarlarkMethod) UsesFlags(com.google.copybara.doc.annotations.UsesFlags) DocDefault(com.google.copybara.doc.annotations.DocDefault)

Example 30 with StarlarkMethod

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

the class GitModule method gerritDestination.

@SuppressWarnings("unused")
@StarlarkMethod(name = "gerrit_destination", doc = "Creates a change in Gerrit using the transformed worktree. If this is used in iterative" + " mode, then each commit pushed in a single Copybara invocation will have the" + " correct commit parent. The reviews generated can then be easily done in the" + " correct order without rebasing.", parameters = { @Param(name = "url", named = true, doc = "Indicates the URL to push to as well as the URL from which to get the parent " + "commit"), @Param(name = "fetch", named = true, doc = "Indicates the ref from which to get the parent commit"), @Param(name = "push_to_refs_for", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, defaultValue = "None", named = true, doc = "Review branch to push the change to, for example setting this to 'feature_x'" + " causes the destination to push to 'refs/for/feature_x'. It defaults to " + "'fetch' value."), @Param(name = "submit", named = true, doc = "If true, skip the push thru Gerrit refs/for/branch and directly push to branch." + " This is effectively a git.destination that sets a Change-Id", defaultValue = "False"), @Param(name = "partial_fetch", defaultValue = "False", named = true, doc = "This is an experimental feature that only works for certain origin globs."), @Param(name = "notify", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "" + "Type of Gerrit notify option (https://gerrit-review.googlesource.com/Docum" + "entation/user-upload.html#notify). Sends notifications by default.", defaultValue = "None"), @Param(name = "change_id_policy", defaultValue = "'FAIL_IF_PRESENT'", named = true, doc = "What to do in the presence or absent of Change-Id in message:" + "<ul>" + "  <li>`'REQUIRE'`: Require that the change_id is present in the message as a" + " valid label</li>" + "  <li>`'FAIL_IF_PRESENT'`: Fail if found in message</li>" + "  <li>`'REUSE'`: Reuse if present. Otherwise generate a new one</li>" + "  <li>`'REPLACE'`: Replace with a new one if found</li>" + "</ul>"), @Param(name = "allow_empty_diff_patchset", named = true, doc = "By default Copybara will upload a new PatchSet to Gerrit without checking the" + " previous one. If this set to false, Copybara will download current PatchSet" + " and check the diff against the new diff.", defaultValue = "True"), @Param(name = "reviewers", named = true, defaultValue = "[]", doc = "The list of the reviewers will be added to gerrit change reviewer listThe element" + " in the list is: an email, for example: \"foo@example.com\" or label for" + " example: ${SOME_GERRIT_REVIEWER}. These are under the condition of" + " assuming that users have registered to gerrit repos"), @Param(name = "cc", named = true, defaultValue = "[]", doc = "The list of the email addresses or users that will be CCed in the review. Can" + " use labels as the `reviewers` field."), @Param(name = "labels", named = true, defaultValue = "[]", doc = "The list of labels to be pushed with the change. The format is the label " + "along with the associated value. For example: Run-Presubmit+1"), @Param(name = "api_checker", allowedTypes = { @ParamType(type = Checker.class), @ParamType(type = NoneType.class) }, defaultValue = "None", doc = "A checker for the Gerrit API endpoint provided for after_migration hooks. " + "This field is not required if the workflow hooks don't use the " + "origin/destination endpoints.", named = true, positional = false), @Param(name = "integrates", allowedTypes = { @ParamType(type = Sequence.class, generic1 = GitIntegrateChanges.class), @ParamType(type = NoneType.class) }, named = true, defaultValue = "None", doc = "Integrate changes from a url present in the migrated change" + " label. Defaults to a semi-fake merge if COPYBARA_INTEGRATE_REVIEW label is" + " present in the message", positional = false), @Param(name = "topic", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, defaultValue = "None", named = true, positional = false, doc = "" + "Sets the topic of the Gerrit change created.<br><br>" + "By default it sets no topic. This field accepts a template with labels. " + "For example: `\"topic_${CONTEXT_REFERENCE}\"`"), @Param(name = "gerrit_submit", defaultValue = "False", named = true, positional = false, doc = "By default, Copybara uses git commit/push to the main branch when submit = True." + "  If this flag is enabled, it will update the Gerrit change with the " + "latest commit and submit using Gerrit."), @Param(name = "primary_branch_migration", allowedTypes = { @ParamType(type = Boolean.class) }, defaultValue = "False", named = true, positional = false, doc = "When enabled, copybara will ignore the 'push_to_refs_for' and 'fetch' params if" + " either is 'master' or 'main' and instead try to establish the default git" + " branch. If this fails, it will fall back to the param's declared value.\n" + "This is intended to help migrating to the new standard of using 'main'" + " without breaking users relying on the legacy default."), @Param(name = "checker", allowedTypes = { @ParamType(type = Checker.class), @ParamType(type = NoneType.class) }, defaultValue = "None", doc = "A checker that validates the commit files & message. If `api_checker` is not" + " set, it will also be used for checking API calls. If only `api_checker`" + "is used, that checker will only apply to API calls.", named = true, positional = false) }, useStarlarkThread = true)
@UsesFlags(GitDestinationOptions.class)
@DocDefault(field = "push_to_refs_for", value = "fetch value")
public GerritDestination gerritDestination(String url, String fetch, Object pushToRefsFor, Boolean submit, Boolean partialFetch, Object notifyOptionObj, String changeIdPolicy, Boolean allowEmptyPatchSet, // <String>
Sequence<?> reviewers, // <String>
Sequence<?> ccParam, // <String>
Sequence<?> labelsParam, Object apiChecker, Object integrates, Object topicObj, Boolean gerritSubmit, Boolean primaryBranchMigrationMode, Object checker, StarlarkThread thread) throws EvalException {
    checkNotEmpty(url, "url");
    if (gerritSubmit) {
        Preconditions.checkArgument(submit, "Only set gerrit_submit if submit is true");
    }
    List<String> newReviewers = SkylarkUtil.convertStringList(reviewers, "reviewers");
    List<String> cc = SkylarkUtil.convertStringList(ccParam, "cc");
    List<String> labels = SkylarkUtil.convertStringList(labelsParam, "labels");
    String notifyOptionStr = convertFromNoneable(notifyOptionObj, null);
    check(!(submit && notifyOptionStr != null), "Cannot set 'notify' with 'submit = True' in git.gerrit_destination().");
    String topicStr = convertFromNoneable(topicObj, null);
    check(!(submit && topicStr != null), "Cannot set 'topic' with 'submit = True' in git.gerrit_destination().");
    NotifyOption notifyOption = notifyOptionStr == null ? null : stringToEnum("notify", notifyOptionStr, NotifyOption.class);
    Checker apiCheckerObj = convertFromNoneable(apiChecker, null);
    Checker checkerObj = convertFromNoneable(checker, null);
    return GerritDestination.newGerritDestination(options, fixHttp(url, thread.getCallerLocation()), checkNotEmpty(firstNotNull(options.get(GitDestinationOptions.class).fetch, fetch), "fetch"), checkNotEmpty(firstNotNull(convertFromNoneable(pushToRefsFor, null), options.get(GitDestinationOptions.class).fetch, fetch), "push_to_refs_for"), submit, partialFetch, notifyOption, stringToEnum("change_id_policy", changeIdPolicy, ChangeIdPolicy.class), allowEmptyPatchSet, newReviewers, cc, labels, apiCheckerObj != null ? apiCheckerObj : checkerObj, Starlark.isNullOrNone(integrates) ? defaultGitIntegrate : Sequence.cast(integrates, GitIntegrateChanges.class, "integrates"), topicStr, gerritSubmit, primaryBranchMigrationMode, checkerObj);
}
Also used : NotifyOption(com.google.copybara.git.GerritDestination.NotifyOption) Checker(com.google.copybara.checks.Checker) ChangeIdPolicy(com.google.copybara.git.GerritDestination.ChangeIdPolicy) StarlarkMethod(net.starlark.java.annot.StarlarkMethod) UsesFlags(com.google.copybara.doc.annotations.UsesFlags) DocDefault(com.google.copybara.doc.annotations.DocDefault)

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