### Example Usage of git.origin Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Example of invoking Copybara with `git.origin` using a GitHub pull request as the origin URL and reference. ```bash copybara copy.bara.sky my_workflow https://github.com/some_project/pull/1784 ``` -------------------------------- ### List Slicing Operations Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Provides examples of list slicing with different start, end, and step values. ```python ['a', 'b', 'c', 'd'][1:3] # ['b', 'c'] ['a', 'b', 'c', 'd'][::2] # ['a', 'c'] ['a', 'b', 'c', 'd'][3:0:-1] # ['d', 'c', 'b'] ``` -------------------------------- ### core.replace Examples Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Examples demonstrating the usage of the core.replace function for various text manipulation tasks, including regex-based replacement, removal of confidential blocks, and conditional replacement with ignore patterns. ```APIDOC ## core.replace: Replace using regex groups ### Description Replaces text based on a regular expression, capturing groups to use in the replacement string. ### Method core.replace ### Endpoint N/A (Function call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **before** (string) - Required - The pattern to search for. - **after** (string) - Required - The replacement string. - **regex_groups** (object) - Required - A map of named capture groups to their regex patterns. ### Request Example ```python core.replace( before = "https://some_internal/url/${pkg}.html", after = "https://example.com/${pkg}.html", regex_groups = { "pkg": ".*", }, ) ``` ### Response N/A (Function modifies content directly) ## core.replace: Remove confidential blocks ### Description Removes blocks of text marked by specific start and end delimiters, often used for confidential information. ### Method core.replace ### Endpoint N/A (Function call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **before** (string) - Required - Placeholder for the pattern to be removed. - **after** (string) - Required - An empty string to effectively remove the matched content. - **multiline** (bool) - Optional - Enables multiline matching for the regex. - **regex_groups** (object) - Required - Defines the regex pattern to identify confidential blocks (e.g., `(?m)^.*BEGIN-INTERNAL[\w\W]*?END-INTERNAL.*$\n`). ### Request Example ```python core.replace( before = "${x}", after = "", multiline = True, regex_groups = { "x": "(?m)^.*BEGIN-INTERNAL[\\w\\W]*?END-INTERNAL.*$\\n", }, ) ``` ### Response N/A (Function modifies content directly) ## core.replace: Replace with ignore ### Description Replaces a pattern with a specified string, while ignoring lines that match a given ignore pattern. ### Method core.replace ### Endpoint N/A (Function call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **before** (string) - Required - The pattern to search for. - **after** (string) - Required - The replacement string. - **regex_groups** (object) - Required - A map of named capture groups to their regex patterns. - **ignore** (list of strings) - Optional - A list of regex patterns for lines to ignore. ### Request Example ```python core.replace( before = "${x}", after = "(broken link)", regex_groups = { "x": "(go|goto)/[-/_#a-zA-Z0-9?]*(.md|)", }, ignore = [".*bazelbuild/rules_go/.*"], ) ``` ### Response N/A (Function modifies content directly) ``` -------------------------------- ### GET /repos/{owner}/{repo}/check-runs Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Get the list of check runs for a sha. ```APIDOC ## GET /repos/{owner}/{repo}/check-runs ### Description Get the list of check runs for a sha. https://developer.github.com/v3/checks/runs/#check-runs ### Method GET ### Endpoint /repos/{owner}/{repo}/check-runs ### Parameters #### Query Parameters - **sha** (string) - Required - The SHA-1 for which we want to get the check runs ``` -------------------------------- ### Create Go proxy version list Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Example of how to create a version list for a given Go package using the go.go_proxy_version_list function. Ensure the module path is correctly specified. ```python go.go_proxy_version_list( module='github.com/google/gopacket' ) ``` -------------------------------- ### Python zip() function examples Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Demonstrates the usage of the built-in zip() function in Python for combining iterables. The output list's size is determined by the shortest input iterable. ```python zip() # == [] ``` ```python zip([1, 2]) # == [(1,), (2,)] ``` ```python zip([1, 2], [3, 4]) # == [(1, 3), (2, 4)] ``` ```python zip([1, 2], [3, 4, 5]) # == [(1, 3), (2, 4)] ``` -------------------------------- ### Get Origin API Handle Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns an API handle for the origin repository. Use with caution as external calls can lead to non-deterministic or irreversible side effects. ```python ctx.origin_api() ``` -------------------------------- ### Define Git Destination with Integration Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md This example shows how to configure a git.destination to automatically integrate changes. It uses the default git.integrate() which looks for the 'COPYBARA_INTEGRATE_REVIEW' label and performs a semi-fake merge, including non-destination file changes. ```python git.destination( url = "https://example.com/some_git_repo", integrates = [git.integrate()], ) ``` -------------------------------- ### Create and Initialize a List Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Demonstrates the creation of a list with initial integer values. ```python x = [1, 2, 3] ``` -------------------------------- ### GET /user Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Get authenticated user info, return null if not found. ```APIDOC ## GET /user ### Description Get authenticated user info, return null if not found. ### Method GET ### Endpoint /user ``` -------------------------------- ### Create index-item pairs with enumerate Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use enumerate to create a list of tuples, where each tuple contains the index and the corresponding item from an input sequence. The optional 'start' parameter specifies the initial index. ```python enumerate([24, 21, 84]) == [(0, 24), (1, 21), (2, 84)] ``` -------------------------------- ### github_create_release_obj.with_body Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Sets the main content or description for the release. ```APIDOC ## github_create_release_obj.with_body ### Description Set the body for the release. ### Method Not specified (likely a builder method) ### Endpoint Not applicable (object method) ### Parameters #### Query Parameters - **body** (string) - Required - Body for the release ### Request Example ```json { "body": "Release notes content here." } ``` ### Response (No specific response documented for this method, likely returns the modified object) #### Success Response (200) (Not specified) #### Response Example (Not specified) ``` -------------------------------- ### HTTP GET Request Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Executes an HTTP GET request to a specified URL with optional headers and authentication. ```APIDOC ## GET /api/http_endpoint ### Description Executes a GET request. ### Method GET ### Endpoint /api/http_endpoint ### Parameters #### Query Parameters - **url** (string) - Required - The URL to send the GET request to. - **headers** (dict) - Optional - A dictionary of HTTP headers for the request. - **auth** (bool) - Optional - Specifies whether to include authentication credentials. ### Response #### Success Response (200) - **http_response** (object) - The HTTP response object. #### Response Example ```json { "status": 200, "body": "..." } ``` ``` -------------------------------- ### Buildozer Commands Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Commands for interacting with Buildozer. ```APIDOC ## buildozer.cmd ### Description Executes a Buildozer command. ### Method Not specified. ### Endpoint N/A ### Parameters None explicitly defined. ### Request Example N/A ### Response N/A ``` ```APIDOC ## buildozer.create ### Description Creates a Buildozer configuration. ### Method Not specified. ### Endpoint N/A ### Parameters None explicitly defined. ### Request Example N/A ### Response N/A ``` ```APIDOC ## buildozer.delete ### Description Deletes a Buildozer configuration. ### Method Not specified. ### Endpoint N/A ### Parameters None explicitly defined. ### Request Example N/A ### Response N/A ``` ```APIDOC ## buildozer.modify ### Description Modifies a Buildozer configuration. ### Method Not specified. ### Endpoint N/A ### Parameters None explicitly defined. ### Request Example N/A ### Response N/A ``` ```APIDOC ## buildozer.print ### Description Prints Buildozer configuration details. ### Method Not specified. ### Endpoint N/A ### Parameters None explicitly defined. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Execute HTTP GET Request Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use this function to perform an HTTP GET request. It accepts a URL, optional headers, and an authentication flag. ```python http_endpoint.get(url, headers={}, auth=False) ``` -------------------------------- ### Python Dictionary Basics Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Demonstrates basic dictionary operations including initialization, iteration, key removal, value assignment, and membership testing. Note that iteration order is preserved. ```python d = {0: "x", 2: "z", 1: "y"} [k for k in d] # [0, 2, 1] d.pop(2) d[0], d[2] = "a", "b" 0 in d, "a" in d # (True, False) [(k, v) for k, v in d.items()] # [(0, "a"), (1, "y"), (2, "b")] ``` -------------------------------- ### Get current timezone-aware datetime Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use datetime.now to get the current timezone-aware StarlarkDateTime object. The 'tz' parameter allows specifying the desired timezone. ```python datetime.now(tz='America/Los_Angeles') ``` -------------------------------- ### Create Buildozer Command Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Creates a Buildozer command. The 'forward' parameter specifies the command, and 'reverse' can be provided for commands that are not automatically reversible. ```python buildozer.cmd(forward, reverse=None) ``` -------------------------------- ### Starlark String Literals and Slicing Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Demonstrates the creation of single-quoted, double-quoted, and multiline string literals. Also shows how to use slicing with positive and negative indices. ```python a = 'abc\ndef' b = "ab'cd" c = """multiline string""" # Strings support slicing (negative index starts from the end): x = "hello"[2:4] # "ll" y = "hello"[1:-1] # "ell" z = "hello"[:4] # "hell" ``` -------------------------------- ### Generate a range of numbers Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Creates a list of numbers from start to stop with a given step. If one argument is provided, it defines the stop value and the start defaults to 0. The step defaults to 1. ```python range(4) == [0, 1, 2, 3] range(3, 9, 2) == [3, 5, 7] range(3, 0, -1) == [3, 2, 1] ``` -------------------------------- ### Buildozer Command Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Creates a Buildozer command, optionally specifying its reversal. ```APIDOC ## buildozer.cmd ### Description Creates a Buildozer command. You can specify the reversal with the 'reverse' argument. ### Method buildozer.cmd(forward, reverse=None) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **forward** (string) - Required - Specifies the Buildozer command, e.g. 'replace deps :foo :bar' - **reverse** (string or NoneType) - Optional - The reverse of the command. This is only required if the given command cannot be reversed automatically and the reversal of this command is required by some workflow or Copybara check. The following commands are automatically reversible: add, remove (when used to remove element from list i.e. 'remove srcs foo.cc'), replace. ### Request Example ```json { "forward": "add deps :my_lib", "reverse": "remove deps :my_lib" } ``` ### Response #### Success Response (200) - **command** (object) - A Buildozer command object. #### Response Example ```json { "command": { "type": "buildozer_cmd", "forward": "add deps :my_lib", "reverse": "remove deps :my_lib" } } ``` ``` -------------------------------- ### go.go_proxy_resolver Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Go resolver that knows what to do with command line passed refs. ```APIDOC ## go.go_proxy_resolver ### Description Go resolver that knows what to do with command line passed refs. ### Method N/A (Function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### gerrit_api_obj.list_changes Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Get changes from Gerrit based on a query. ```APIDOC ## GET /api/changes/ ### Description Get changes from Gerrit based on a query. See https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes. ### Method GET ### Endpoint /api/changes/ ### Parameters #### Query Parameters - **query** (string) - Required - The query string to list changes by. See https://gerrit-review.googlesource.com/Documentation/user-search.html#_basic_change_search. - **include_results** (sequence of string) - Optional - What to include in the response. See https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#query-options ### Response #### Success Response (200) - **list of gerritapi.ChangeInfo** - A list of Gerrit changes matching the query. ``` -------------------------------- ### string.index Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns the first index of a substring, with optional start and end bounds. ```APIDOC ## string.index ### Description Returns the first index where `sub` is found, or raises an error if no such index exists, optionally restricting to `[start:end]`. ### Method string.index ### Parameters #### Path Parameters - **self** (string) - Required - This string. - **sub** (string) - Required - The substring to find. - **start** (int or NoneType) - Optional - Restrict to search from this position. - **end** (int or NoneType) - Optional - Optional position before which to restrict to search. ### Response #### Success Response (200) - **index** (int) - The first index where the substring is found. #### Response Example ```json { "example": "hello world".index("world") } ``` ``` -------------------------------- ### go.go_proxy_version_list Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns go proxy version list object. ```APIDOC ## go.go_proxy_version_list ### Description Returns go proxy version list object. ### Method N/A (Function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python go.go_proxy_version_list( module='github.com/google/gopacket' ) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### buildozer.print Transformation Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Executes a buildozer print command and returns the output, designed for use within transforms. ```APIDOC ## buildozer.print ### Description Executes a buildozer print command and returns the output. This is designed to be used in the context of a transform. ### Method buildozer.print ### Parameters #### Path Parameters - **ctx** (TransformWork) - Required - The TransformWork object. - **attr** (string) - Required - The attribute from the target rule to print. - **target** (string) - Required - The target to print from. ### Response #### Success Response (200) - **output** (string) - The output of the buildozer print command. ``` -------------------------------- ### Get HTTP Response Contents as String Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Retrieves the content of an HTTP response as a string. ```python http_response.contents_string() ``` -------------------------------- ### Get Dictionary Keys Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns a list of all keys in the dictionary. The order of keys is not guaranteed. ```python {2: "a", 4: "b", 1: "c"}.keys() == [2, 4, 1] ``` -------------------------------- ### Copybara CLI Flags Reference Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md A comprehensive list of available command-line flags for Copybara, including their types, descriptions, and usage. ```APIDOC ## Copybara CLI Flags This section details the various flags that can be used with the Copybara command-line interface. ### `--labels` * **Description**: Additional flags that can be accessed in feedback and mirror context objects via the `cli_labels` field. In `core.workflow`, they are accessible as labels, but with names uppercased and prefixed with `FLAG_` to avoid name clashes with existing labels. For example, `--labels=label1:value1` will define a label `FLAG_LABEL1`. * **Format**: `--labels=flag1:value1,flag2:value2` or `--labels flag1:value1,flag2:value2` * **Type**: `immutableMap` ### `--noansi` * **Description**: Disables ANSI output for messages. * **Type**: `boolean` ### `--nocleanup` * **Description**: Controls whether to clean up output directories (workdir, scratch clones of Git repos, etc.) before execution. By default, directories are cleaned (`false`). If set to `true`, previous run output will not be cleaned up, potentially leading to increased disk usage. * **Type**: `boolean` ### `--nogit-credential-helper-store` * **Description**: Disables the use of the Git credentials store. See https://git-scm.com/docs/git-credential-store for more information. * **Type**: `boolean` ### `--nogit-prompt` * **Description**: Disables username/password prompts and causes the command to fail if no credentials are found. This flag sets the `GIT_TERMINAL_PROMPT` environment variable, intended for automated jobs running Git. See https://git-scm.com/docs/git/2.3.0#git-emGITTERMINALPROMPTem. * **Type**: `boolean` ### `--noprompt` * **Description**: Disables prompts, automatically answering all prompts with 'yes'. * **Type**: `boolean` ### `--output-limit` * **Description**: Limits the output displayed in the console to a specified number of records. The default is `0`, which shows all output. Each subcommand might interpret this flag differently. * **Type**: `int` ### `--output-root` * **Description**: Specifies the root directory for generating output files. If not set, `~/copybara/out` is used by default. Use with caution, as Copybara may remove files within this directory. * **Type**: `string` ### `--patch-bin` * **Description**: Specifies the path to the GNU Patch command. * **Type**: `string` ### `--remote-http-files-connection-timeout` * **Description**: Sets the timeout duration for fetch operations. Example values: `30s`, `20m`, `1h`. * **Type**: `duration` ### `--repo-timeout` * **Description**: Sets the timeout duration for repository operations. Example values: `30s`, `20m`, `1h`. * **Type**: `duration` ### `--squash` * **Description**: Overrides the workflow's mode to `SQUASH`. This is primarily useful for workflows using `ITERATIVE` mode when a single export is needed, perhaps to fix an issue. It is recommended to always use `--dry-run` before applying this flag to test changes locally. * **Type**: `boolean` ### `--validate-starlark` * **Description**: Validates Starlark code prior to execution. This might break legacy configurations. Options include `LOOSE` and `STRICT`. * **Type**: `string` ### `--version-selector-use-cli-ref` * **Description**: If a command-line reference is used with a version selector, this flag tells Copybara to use it. * **Type**: `boolean` ### `-v, --verbose` * **Description**: Enables verbose output. * **Type**: `boolean` ``` -------------------------------- ### ctx.fill_template Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Replaces variables in templates with the values from this revision. Example: 'Current Revision: ${GIT_SHORT_SHA1}'. ```APIDOC ## ctx.fill_template ### Description Replaces variables in templates with the values from this revision. ### Method ctx.fill_template ### Parameters #### Path Parameters - **template** (string) - Required - The template to use ### Request Example ```python filled_template = ctx.fill_template('Current Revision: ${GIT_SHORT_SHA1}') ``` ### Response #### Success Response (200) - **filled_template** (string) - The template with variables replaced. ``` -------------------------------- ### archive.create Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Creates an archive from a list of files, optionally compressed. ```APIDOC ## archive.create ### Description Creates an archive, possibly compressed, from a list of files. ### Method Not specified (function call syntax used) ### Endpoint Not applicable (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **archive** (Path) - Required - Expected path of the generated archive file. - **files** (glob or NoneType) - Optional - An optional glob to describe the list of file paths that are to be included in the archive. If not specified, all files under the current working directory will be included. Note, the original file path in the filesystem will be preserved when archiving it. ### Request Example ```python archive.create(archive="path/to/archive.zip", files="*.txt") ``` ### Response #### Success Response (200) Not specified #### Response Example Not specified ``` -------------------------------- ### string.endswith Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Checks if the string ends with a specified suffix, with optional start and end indices. ```APIDOC ## string.endswith ### Description Returns True if the string ends with `sub`, otherwise False, optionally restricting to `[start:end]`, `start` being inclusive and `end` being exclusive. ### Method string.endswith ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **return_value** (bool) - True if the string ends with the suffix, False otherwise. #### Response Example ```json { "return_value": true } ``` ``` -------------------------------- ### Get HTTP Response Status Code Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Retrieves the HTTP status code from a response object. ```python http_response.code() ``` -------------------------------- ### buildozer.create Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Creates a new build target and populates its attributes. This transform can reverse automatically to delete the target. ```APIDOC ## buildozer.create ### Description A transformation which creates a new build target and populates its attributes. This transform can reverse automatically to delete the target. ### Method Not applicable (this is a transformation function, not an HTTP endpoint) ### Endpoint Not applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python buildozer.create(target='foo:bar', rule_type='java_library', commands=['add deps :dependency'], before='other_target') ``` ### Response #### Success Response (200) None (this is a transformation function) #### Response Example None ``` -------------------------------- ### Get Length of Iterable Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns the number of items in a string, sequence, dictionary, set, or other iterable. ```python int(len(x)) ``` -------------------------------- ### Create Customizable Dynamic Transformation Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Create a customizable dynamic transformation by defining an implementation function and an exposed function that accepts parameters. The implementation function uses parameters available under ctx.params. ```python def _test_impl(ctx): ctx.set_message(ctx.message + ctx.params['name'] + str(ctx.params['number']) + '\n') ``` ```python def test(name, number = 2): return core.dynamic_transform(impl = _test_impl, params = { 'name': name, 'number': number}) ``` -------------------------------- ### Define a Dynamic Transformation Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Example of defining a custom transformation function that returns a successful status. ```python def my_transform(ctx): # do some stuff return ctx.success() ``` -------------------------------- ### goproxy_version_list.get_info Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Return the results of an info query. An object is only returned if a ref was specified. ```APIDOC ## goproxy_version_list.get_info ### Description Return the results of an info query. An object is only returned if a ref was specified. ### Method N/A (Function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Python set.pop() Example Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Removes and returns an arbitrary element from the set. Fails if the set is empty. ```python s = set([3, 1, 2]) s.pop() # 3; s == set([1, 2]) s.pop() # 1; s == set([2]) s.pop() # 2; s == set() s.pop() # error: empty set ``` -------------------------------- ### Define a Copybara Migration Workflow Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use core.workflow to define a migration pipeline. Configure origin, destination, authoring, transformations, and file filtering. Optional parameters control behavior like dry runs, confirmation prompts, and rev ID settings. ```python core.workflow( name="my_workflow", origin=git.origin( repo="https://github.com/google/copybara", ref="refs/heads/main" ), destination=git.destination( repo="https://github.com/google/copybara-destination", ref="refs/heads/main" ), authoring=authoring.pass_through(), transformations=[ core.subworkflow( "my_subworkflow", [ move.move(src="source/dir", dst="destination/dir") ] ) ], origin_files=glob(["**"]), destination_files=glob(["**"]), mode="SQUASH", reversible_check=True, check_last_rev_state=False, ask_for_confirmation=False, dry_run=False, after_migration=[], after_workflow=[], change_identity=None, set_rev_id=True, smart_prune=False, merge_import=None, autopatch_config=None, after_merge_transformations=[], migrate_noop_changes=False, experimental_custom_rev_id=None, custom_rev_id=None, description=None, checkout=True, reversible_check_ignore_files=None, consistency_file_path=None ) ``` -------------------------------- ### POST /repos/{owner}/{repo}/releases Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Creates a new GitHub release. ```APIDOC ## POST /repos/{owner}/{repo}/releases ### Description Create a new GitHub release. ### Method POST ### Endpoint /repos/{owner}/{repo}/releases ### Parameters #### Request Body - **request** (github_create_release_obj) - Required - The populated release object. See new_release_request. ``` -------------------------------- ### Get Number of Regex Groups Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns the total number of capturing groups found in a regex match. ```python re2_matcher.group_count() ``` -------------------------------- ### Get HTTP Response Status Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Retrieves the HTTP status message of a response. This function takes no arguments. ```Starlark http_response.status() ``` -------------------------------- ### Get Dictionary Values Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns a list of all values in the dictionary. The order of values corresponds to the order of keys. ```python {2: "a", 4: "b", 1: "c"}.values() == ["a", "b", "c"] ``` -------------------------------- ### Python set.issuperset() Examples Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns true if the set is a superset of another collection. A set is always a superset of itself. ```python set([1, 2, 3]).issuperset([1, 2]) # True set([1, 2, 3]).issuperset([1, 2, 3]) # True set([1, 2, 3]).issuperset([2, 3, 4]) # False ``` -------------------------------- ### Add Setting to Multiple Targets with Buildozer Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use buildozer.modify to apply a configuration setting to multiple targets simultaneously. Provide a list of targets and the command to execute. ```python buildozer.modify( target = ['foo/bar:baz', 'foo/bar:fooz'], commands = [ buildozer.cmd('set config ":foo"'), ], ) ``` -------------------------------- ### credentials.toml_key_source Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Supply an authentication credential from a TOML file. ```APIDOC ## credentials.toml_key_source ### Description Supply an authentication credential from the file pointed to by the --http-credential-file flag. ### Method CredentialIssuer credentials.toml_key_source(dot_path) ### Parameters #### Path Parameters - **dot_path** (string) - Required - Dot path to the data field containing the credential. ``` -------------------------------- ### Python set.issubset() Examples Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns true if the set is a subset of another collection. A set is always a subset of itself. ```python set([1, 2]).issubset([1, 2, 3]) # True set([1, 2]).issubset([1, 2]) # True set([1, 2]).issubset([2, 3]) # False ``` -------------------------------- ### core.dynamic_feedback Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Creates a dynamic Skylark feedback migration. Intended for library developers. ```APIDOC ## core.dynamic_feedback ### Description Create a dynamic Skylark feedback migration. This should only be used by libraries developers ### Method Not specified (likely internal or part of a larger framework) ### Endpoint Not applicable (Skylark function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **impl** (callable) - Required - The Skylark function to call. - **params** (dict) - Optional - The parameters to the function. Will be available under ctx.params. ``` -------------------------------- ### string.count Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns the number of non-overlapping occurrences of a substring within a string, with optional start and end indices. ```APIDOC ## string.count ### Description Returns the number of (non-overlapping) occurrences of substring `sub` in string, optionally restricting to `[start:end]`, `start` being inclusive and `end` being exclusive. ### Method string.count ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **return_value** (int) - The number of occurrences of the substring. #### Response Example ```json { "return_value": 5 } ``` ``` -------------------------------- ### Get HTML element attribute Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Retrieves the value of a specified attribute from an HTML element. The attribute key is case-sensitive. ```python html_element.attr(key) ``` -------------------------------- ### String Slicing Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Demonstrates advanced string slicing with step and negative indexing. Use slicing to extract substrings. ```python s = "hello"[::2] # "hlo" ``` ```python t = "hello"[3:0:-1] # "lle" ``` -------------------------------- ### Python set.isdisjoint() Examples Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns true if the set has no elements in common with another collection. Works with empty sets. ```python set([1, 2]).isdisjoint([3, 4]) # True set().isdisjoint(set()) # True set([1, 2]).isdisjoint([2, 3]) # False ``` -------------------------------- ### git.mirrorContext.success Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns a successful action result. ```APIDOC ## git.mirrorContext.success ### Description Returns a successful action result. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json git.mirrorContext.success() ``` ### Response #### Success Response (200) - **dynamic.action_result** - Represents a successful outcome of an action. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Create Folder Origin Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use folder.origin() to create an origin that reads input from a local folder. The folder path is specified via the source_ref argument. Consider the materialize_outside_symlinks flag for handling symlinks. ```python folder.origin(materialize_outside_symlinks=False) ``` -------------------------------- ### Get Current Date as String Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Retrieves the current date formatted as a string. Allows specifying the date format and timezone. ```python ctx.now_as_string(format="yyyy-MM-dd", zone="UTC") ``` -------------------------------- ### Move Files Between Directories with core.move Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use core.move to relocate files and directories. It supports glob patterns for selecting files and can rename files during the move. Overwriting is optional. ```python core.move("foo/bar_internal", "bar") ``` ```python core.move("", "foo") ``` ```python core.move("foo", "") ``` ```python core.move(before = 'foo/${x}.txt', after = 'foo/${x}.md', regex_groups = { 'x': '.*'}) ``` -------------------------------- ### Get String Elements in Python Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns an iterable of 1-element substrings from the string. This is equivalent to a list comprehension iterating through each character. ```python list of string string.elems(self) ``` -------------------------------- ### Get Regex Match Group Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns the string captured by a specified matching group. Defaults to group 0 if not specified. ```python re2_matcher.group(group=0) ``` -------------------------------- ### Create Folder Destination Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use folder.destination() to create a destination that writes output to a local folder. This is useful for testing or simple migrations. Note limitations regarding ref passing, history support, and mode usage. ```python folder.destination() ``` -------------------------------- ### getattr() - Get Struct Attribute Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Retrieves an attribute from a struct by its name. Optionally provides a default value if the attribute does not exist. ```APIDOC ## getattr() ### Description Returns the struct's field of the given name if it exists. If not, it either returns `default` (if specified) or raises an error. `getattr(x, "foobar")` is equivalent to `x.foobar`. ### Method N/A (Function call) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python getattr(ctx.attr, "myattr") getattr(ctx.attr, "myattr", "mydefault") ``` ### Response #### Success Response (200) - **unknown** - The value of the requested attribute, or the default value if specified and the attribute does not exist. #### Response Example ```json "attribute_value" ``` ``` -------------------------------- ### enumerate() - Enumerate Sequence Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns a list of pairs (index, item) from an input sequence. An optional start index can be provided. ```APIDOC ## enumerate() ### Description Returns a list of pairs (two-element tuples), with the index (int) and the item from the input sequence. ### Method N/A (Function call) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python enumerate([24, 21, 84]) == [(0, 24), (1, 21), (2, 84)] enumerate(["a", "b"], start=1) == [(1, "a"), (2, "b")] ``` ### Response #### Success Response (200) - **list** - A list of tuples, where each tuple contains an index and an item from the input sequence. #### Response Example ```json [(0, 24), (1, 21), (2, 84)] ``` ``` -------------------------------- ### github_create_release_obj.with_name Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Sets a custom display name for the release. ```APIDOC ## github_create_release_obj.with_name ### Description Set the name for the release. ### Method Not specified (likely a builder method) ### Endpoint Not applicable (object method) ### Parameters #### Query Parameters - **name** (string) - Required - Name for the release ### Request Example ```json { "name": "v1.0.0 Release" } ``` ### Response (No specific response documented for this method, likely returns the modified object) #### Success Response (200) (Not specified) #### Response Example (Not specified) ``` -------------------------------- ### http.host Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Wraps a host with optional authentication credentials for HTTP requests. ```APIDOC ## http.host ### Description Wraps a host and potentially credentials for http auth. ### Method Not specified (function signature provided) ### Endpoint Not specified (function signature provided) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python http.host(host='example.com', auth=my_auth_interceptor) ``` ### Response #### Success Response (200) Not specified #### Response Example Not specified ``` -------------------------------- ### Get HTTP Response Header Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Retrieves the value of a specific HTTP response header by its key. Requires the header key as input. ```Starlark http_response.header(key) ``` -------------------------------- ### Copy Files Between Directories Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use core.copy to move files or directories. Specify 'before' and 'after' paths. Use 'paths' to filter files and 'overwrite' to replace existing ones. 'regex_groups' can rename files based on regex matches. ```python core.copy("foo/bar_internal", "bar") ``` ```python core.copy(before = 'foo/${x}.txt', after = 'foo/${x}.md', regex_groups = { 'x': '.*'}) ``` ```python core.transform( [core.copy("foo", "foo/static", paths = glob(["**.css","**.html", ]))], reversal = [core.remove(glob(['foo/static/**.css', 'foo/static/**.html']))] ) ``` -------------------------------- ### Get All GitHub References SHA-1s Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Fetches SHA-1 hashes for all references in a GitHub repository. Note that Copybara has a limit of 500 references. ```python github_api_obj.get_references() ``` -------------------------------- ### Generate Squash Notes with Custom Prefix and Compact Disabled Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md This snippet demonstrates generating squash notes with a custom prefix and disabling the compact format. This allows for more detailed commit messages, including full commit descriptions and extended text. ```python metadata.squash_notes( prefix = 'Changes for Project Foo:', compact = False ) ``` -------------------------------- ### Calculate MD5 hash of a file Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use this function to get the MD5 hash of a file. It is recommended to use this only for legacy systems that require MD5. ```python hashing.path_md5_sum(path) ``` -------------------------------- ### Remove and Get First Dictionary Item Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Removes and returns the first (key, value) pair from the dictionary. This method fails if the dictionary is empty. ```python dict.popitem() ``` -------------------------------- ### Output Object Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Contains descriptive details about a run, including a summary, text details, and a title. ```APIDOC ## output_obj ### Description Descriptive details about the run. ### Fields - **summary** (string) - The summary of the check run. - **text** (string) - The details of the check run. - **title** (string) - The title of the check run. ``` -------------------------------- ### Get Label Values Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Retrieves a list of string values associated with a specific label name. Requires the label name as a string argument. ```Starlark message.label_values(label_name) ``` -------------------------------- ### GoProxy Version List Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Methods for retrieving information about Go proxy versions. ```APIDOC ## GoProxy Version List ### Description Provides methods to get information about Go proxy versions. ### Methods - `get_info()`: Retrieves information about the Go proxy version list. ``` -------------------------------- ### Create GitHub Release Request Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Initializes a request to create a new GitHub release. Requires a tag name. Further details like the release name can be added using chained methods. ```python endpoint.new_release_request(tag_name='v1.0.2').with_name('1.0.2') ``` -------------------------------- ### Python set.intersection_update() Example Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Removes elements not found in all other collections. Accepts sequences and dicts. Can be called without arguments to leave the set unchanged. ```python s = set([1, 2, 3, 4]) s.intersection_update([0, 1, 2]) # None; s is set([1, 2]) s.intersection_update([0, 1], [1, 2]) # None; s is set([1]) ``` -------------------------------- ### string.find Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Finds the first occurrence of a substring within the string and returns its index, or -1 if not found. Supports optional start and end indices. ```APIDOC ## string.find ### Description Returns the first index where `sub` is found, or -1 if no such index exists, optionally restricting to `[start:end]`, `start` being inclusive and `end` being exclusive. ### Method string.find ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **return_value** (int) - The index of the first occurrence of the substring, or -1 if not found. #### Response Example ```json { "return_value": 10 } ``` ``` -------------------------------- ### Find Regex Match in String Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Returns true if the string matches the regex pattern. Optionally, a start position can be provided to begin the search. ```python re2_matcher.find(start=None) ``` -------------------------------- ### Get value from TomlContent Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use this method to retrieve a value associated with a specific key from parsed TOML content. If the key does not exist, it returns None. ```python TomlContent.get("foo") ``` -------------------------------- ### Format String by Name Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use .format() with named arguments to insert values into a string. Arguments are matched by their keyword names. ```python "x{key}x".format(key = 2) ``` -------------------------------- ### Calculate Set Difference Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use `set.difference()` to get a new set with elements in the first set but not in others. Accepts sequences and dicts, unlike the `-` operator. ```python set([1, 2, 3]).difference([2]) # set([1, 3]) ``` ```python set([1, 2, 3]).difference([0, 1], [3, 4]) # set([2]) ``` ```python sequence set.difference(others) ``` -------------------------------- ### core.latest_version Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Selects the latest version that matches the specified format and regex groups. ```APIDOC ## core.latest_version ### Description Selects the latest version that matches the format. Using --force in the CLI will force to use the reference passed as argument instead. ### Method Not specified (likely a function call within Copybara's configuration) ### Endpoint Not applicable (this is a function, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python core.latest_version( format = "refs/tags/${n0}.${n1}.${n2}", regex_groups = { 'n0': '[0-9]+', 'n1': '[0-9]+', 'n2': '[0-9]+' } ) ``` ### Response #### Success Response (200) - **VersionSelector** (object) - An object representing the selected version. #### Response Example ```json { "example": "selected_version_object" } ``` ``` -------------------------------- ### Convert to String Representation (repr) Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Use repr() for debugging to get a string representation of an object. It ensures the output is a string, useful for inspecting values. ```python repr("ab") == '"ab"' ``` -------------------------------- ### Create Archive Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Creates an archive file from a list of files. Supports optional glob for file selection. Preserves original file paths within the archive. ```python archive.create(archive, files=None) ``` -------------------------------- ### String Strip Example Source: https://raw.githubusercontent.com/google/copybara/refs/heads/master/docs/reference.md Removes leading and trailing characters from a string that are present in the 'chars' argument. Note that 'chars' is not a prefix or suffix, but all combinations are removed. ```python "aabcbcbaa".strip("ab") == "cbc" ```