1
1
Fork 0
mirror of https://github.com/mcuadros/ascode synced 2024-05-08 00:26:15 +02:00

starlark/types: standarization of Type and String methods

This commit is contained in:
Máximo Cuadros 2020-03-23 21:18:06 +01:00
parent 030e0b00c5
commit 5ce0598bdc
No known key found for this signature in database
GPG Key ID: 17A5DFEDC735AE4B
24 changed files with 413 additions and 273 deletions

View File

@ -3,36 +3,44 @@ title: 'encoding/base64'
---
base64 defines base64 encoding & decoding functions, often used to represent binary as text.
## Index
* [def <b>decode</b>(src,encoding="standard") string](#def-ibase64ibdecodeb)
* [def <b>encode</b>(src,encoding="standard") string](#def-ibase64ibencodeb)
## Functions
#### def <b>decode</b>
#### def <i>base64</i>.<b>decode</b>
```go
decode(src,encoding="standard") string
base64.decode(src,encoding="standard") string
```
parse base64 input, giving back the plain string representation
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'src' | 'string' | source string of base64-encoded text |
| 'encoding' | 'string' | optional. string to set decoding dialect. allowed values are: standard,standard_raw,url,url_raw |
| `src` | `string` | source string of base64-encoded text |
| `encoding` | `string` | optional. string to set decoding dialect. allowed values are: standard,standard_raw,url,url_raw |
#### def <b>encode</b>
#### def <i>base64</i>.<b>encode</b>
```go
encode(src,encoding="standard") string
base64.encode(src,encoding="standard") string
```
return the base64 encoding of src
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'src' | 'string' | source string to encode to base64 |
| 'encoding' | 'string' | optional. string to set encoding dialect. allowed values are: standard,standard_raw,url,url_raw |
| `src` | `string` | source string to encode to base64 |
| `encoding` | `string` | optional. string to set encoding dialect. allowed values are: standard,standard_raw,url,url_raw |

View File

@ -3,41 +3,49 @@ title: 'encoding/csv'
---
csv reads comma-separated values files
## Index
* [def <b>read_all</b>(source, comma=",", comment="", lazy_quotes=False, trim_leading_space=False, fields_per_record=0, skip=0) [][]string](#def-icsvibread_allb)
* [def <b>write_all</b>(source,comma=",") string](#def-icsvibwrite_allb)
## Functions
#### def <b>read_all</b>
#### def <i>csv</i>.<b>read_all</b>
```go
read_all(source, comma=",", comment="", lazy_quotes=False, trim_leading_space=False, fields_per_record=0, skip=0) [][]string
csv.read_all(source, comma=",", comment="", lazy_quotes=False, trim_leading_space=False, fields_per_record=0, skip=0) [][]string
```
read all rows from a source string, returning a list of string lists
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'source' | 'string' | input string of csv data |
| 'comma' | 'string' | comma is the field delimiter, defaults to "," (a comma). comma must be a valid character and must not be \r, \n, or the Unicode replacement character (0xFFFD). |
| 'comment' | 'string' | comment, if not "", is the comment character. Lines beginning with the comment character without preceding whitespace are ignored. With leading whitespace the comment character becomes part of the field, even if trim_leading_space is True. comment must be a valid character and must not be \r, \n, or the Unicode replacement character (0xFFFD). It must also not be equal to comma. |
| 'lazy_quotes' | 'bool' | If lazy_quotes is True, a quote may appear in an unquoted field and a non-doubled quote may appear in a quoted field. |
| 'trim_leading_space' | 'bool' | If trim_leading_space is True, leading white space in a field is ignored. This is done even if the field delimiter, comma, is white space. |
| 'fields_per_record' | 'int' | fields_per_record is the number of expected fields per record. If fields_per_record is positive, read_all requires each record to have the given number of fields. If fields_per_record is 0, read_all sets it to the number of fields in the first record, so that future records must have the same field count. If fields_per_record is negative, no check is made and records may have a variable number of fields. |
| 'skip' | 'int' | number of rows to skip, omitting from returned rows |
| `source` | `string` | input string of csv data |
| `comma` | `string` | comma is the field delimiter, defaults to "," (a comma). comma must be a valid character and must not be \r, \n, or the Unicode replacement character (0xFFFD). |
| `comment` | `string` | comment, if not "", is the comment character. Lines beginning with the comment character without preceding whitespace are ignored. With leading whitespace the comment character becomes part of the field, even if trim_leading_space is True. comment must be a valid character and must not be \r, \n, or the Unicode replacement character (0xFFFD). It must also not be equal to comma. |
| `lazy_quotes` | `bool` | If lazy_quotes is True, a quote may appear in an unquoted field and a non-doubled quote may appear in a quoted field. |
| `trim_leading_space` | `bool` | If trim_leading_space is True, leading white space in a field is ignored. This is done even if the field delimiter, comma, is white space. |
| `fields_per_record` | `int` | fields_per_record is the number of expected fields per record. If fields_per_record is positive, read_all requires each record to have the given number of fields. If fields_per_record is 0, read_all sets it to the number of fields in the first record, so that future records must have the same field count. If fields_per_record is negative, no check is made and records may have a variable number of fields. |
| `skip` | `int` | number of rows to skip, omitting from returned rows |
#### def <b>write_all</b>
#### def <i>csv</i>.<b>write_all</b>
```go
write_all(source,comma=",") string
csv.write_all(source,comma=",") string
```
write all rows from source to a csv-encoded string
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'source' | '[][]string' | array of arrays of strings to write to csv |
| 'comma' | 'string' | comma is the field delimiter, defaults to "," (a comma). comma must be a valid character and must not be \r, \n, or the Unicode replacement character (0xFFFD). |
| `source` | `[][]string` | array of arrays of strings to write to csv |
| `comma` | `string` | comma is the field delimiter, defaults to "," (a comma). comma must be a valid character and must not be \r, \n, or the Unicode replacement character (0xFFFD). |

View File

@ -3,133 +3,148 @@ title: 'path/filepath'
---
filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file path
## Index
* [def <b>abs</b>(path) string](#def-ifilepathibabsb)
* [def <b>base</b>(path) string](#def-ifilepathibbaseb)
* [def <b>clean</b>(path) string](#def-ifilepathibcleanb)
* [def <b>dir</b>(path) string](#def-ifilepathibdirb)
* [def <b>ext</b>(path) string](#def-ifilepathibextb)
* [def <b>glob</b>(pattern) list](#def-ifilepathibglobb)
* [def <b>is_abs</b>(path) bool](#def-ifilepathibis_absb)
* [def <b>join</b>(elements) string](#def-ifilepathibjoinb)
* [def <b>rel</b>(basepath, targpath) string](#def-ifilepathibrelb)
## Functions
#### def <b>abs</b>
#### def <i>filepath</i>.<b>abs</b>
```go
abs(path) string
filepath.abs(path) string
```
returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'path' | 'string' | relative or absolute path |
| `path` | `string` | relative or absolute path |
#### def <b>base</b>
#### def <i>filepath</i>.<b>base</b>
```go
base(path) string
filepath.base(path) string
```
returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, `base` returns ".". If the path consists entirely of separators, `base` returns a single separator.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'path' | 'string' | input path |
| `path` | `string` | input path |
#### def <b>clean</b>
#### def <i>filepath</i>.<b>clean</b>
```go
clean(path) string
filepath.clean(path) string
```
returns the shortest path name equivalent to path by purely lexical processing.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'path' | 'string' | input path |
| `path` | `string` | input path |
#### def <b>dir</b>
#### def <i>filepath</i>.<b>dir</b>
```go
dir(path) string
filepath.dir(path) string
```
returns all but the last element of path, typically the path's directory. After dropping the final element, `dir` calls `clean` on the path and trailing slashes are removed. If the path is empty, `dir` returns ".". If the path consists entirely of separators, `dir` returns a single separator. The returned path does not end in a separator unless it is the root directory.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'path' | 'string' | input path |
| `path` | `string` | input path |
#### def <b>ext</b>
#### def <i>filepath</i>.<b>ext</b>
```go
ext(path) string
filepath.ext(path) string
```
returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'path' | 'string' | input path |
| `path` | `string` | input path |
#### def <b>glob</b>
#### def <i>filepath</i>.<b>glob</b>
```go
glob(pattern) list
filepath.glob(pattern) list
```
returns the names of all files matching pattern or None if there is no matching file.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'pattern' | 'string' | pattern ([syntax](https://golang.org/pkg/path/filepath/#Match)) |
| `pattern` | `string` | pattern ([syntax](https://golang.org/pkg/path/filepath/#Match)) |
#### def <b>is_abs</b>
#### def <i>filepath</i>.<b>is_abs</b>
```go
is_abs(path) bool
filepath.is_abs(path) bool
```
reports whether the path is absolute.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'path' | 'string' | input path |
| `path` | `string` | input path |
#### def <b>join</b>
#### def <i>filepath</i>.<b>join</b>
```go
join(elements) string
filepath.join(elements) string
```
joins any number of path elements into a single path, adding a `filepath.separator` if necessary. Join calls Clean on the result; in particular, all empty strings are ignored. On Windows, the result is a UNC path if and only if the first path element is a UNC path.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'elements' | 'lists' | list of path elements to be joined |
| `elements` | `lists` | list of path elements to be joined |
#### def <b>rel</b>
#### def <i>filepath</i>.<b>rel</b>
```go
rel(basepath, targpath) string
filepath.rel(basepath, targpath) string
```
returns a relative path that is lexically equivalent to targpath when joined to basepath with an intervening separator. That is, `filepath.join(basepath, filepath.rel(basepath, targpath))` is equivalent to targpath itself. On success, the returned path will always be relative to basepath, even if basepath and targpath share no elements. An error is returned if targpath can't be made relative to basepath or if knowing the current working directory would be necessary to compute it. Rel calls Clean on the result.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'basepath' | 'string' | relative or absolute path |
| 'targpath' | 'string' | relative or absolute path |
| `basepath` | `string` | relative or absolute path |
| `targpath` | `string` | relative or absolute path |

View File

@ -1,149 +1,167 @@
---
title: 'http'
title: ''
---
http defines an HTTP client implementation
## Index
* [def <b>delete</b>(url,params={},headers={},body="",form_body={},json_body={},auth=](#def-ihttpibdeleteb)
* [def <b>get</b>(url,params={},headers={},auth=](#def-ihttpibgetb)
* [def <b>options</b>(url,params={},headers={},body="",form_body={},json_body={},auth=](#def-ihttpiboptionsb)
* [def <b>patch</b>(url,params={},headers={},body="",form_body={},json_body={},auth=](#def-ihttpibpatchb)
* [def <b>post</b>(url,params={},headers={},body="",form_body={},json_body={},auth=](#def-ihttpibpostb)
* [def <b>put</b>(url,params={},headers={},body="",form_body={},json_body={},auth=](#def-ihttpibputb)
* [type <b>response</b>](#type-bresponseb)
* [def <b>body</b>() string](#def-iresponseibbodyb)
* [def <b>json</b>()](#def-iresponseibjsonb)
## Functions
#### def <b>delete</b>
#### def <i>http</i>.<b>delete</b>
```go
delete(url,params={},headers={},body="",form_body={},json_body={},auth=()) response
http.delete(url,params={},headers={},body="",form_body={},json_body={},auth=()) response
```
perform an HTTP DELETE request, returning a response
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'url' | 'string' | url to request |
| 'headers' | 'dict' | optional. dictionary of headers to add to request |
| 'body' | 'string' | optional. raw string body to provide to the request |
| 'form_body' | 'dict' | optional. dict of values that will be encoded as form data |
| 'json_body' | 'any' | optional. json data to supply as a request. handy for working with JSON-API's |
| 'auth' | 'tuple' | optional. (username,password) tuple for http basic authorization |
| `url` | `string` | url to request |
| `headers` | `dict` | optional. dictionary of headers to add to request |
| `body` | `string` | optional. raw string body to provide to the request |
| `form_body` | `dict` | optional. dict of values that will be encoded as form data |
| `json_body` | `any` | optional. json data to supply as a request. handy for working with JSON-API's |
| `auth` | `tuple` | optional. (username,password) tuple for http basic authorization |
#### def <b>get</b>
#### def <i>http</i>.<b>get</b>
```go
get(url,params={},headers={},auth=()) response
http.get(url,params={},headers={},auth=()) response
```
perform an HTTP GET request, returning a response
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'url' | 'string' | url to request |
| 'headers' | 'dict' | optional. dictionary of headers to add to request |
| 'auth' | 'tuple' | optional. (username,password) tuple for http basic authorization |
| `url` | `string` | url to request |
| `headers` | `dict` | optional. dictionary of headers to add to request |
| `auth` | `tuple` | optional. (username,password) tuple for http basic authorization |
#### def <b>options</b>
#### def <i>http</i>.<b>options</b>
```go
options(url,params={},headers={},body="",form_body={},json_body={},auth=()) response
http.options(url,params={},headers={},body="",form_body={},json_body={},auth=()) response
```
perform an HTTP OPTIONS request, returning a response
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'url' | 'string' | url to request |
| 'headers' | 'dict' | optional. dictionary of headers to add to request |
| 'body' | 'string' | optional. raw string body to provide to the request |
| 'form_body' | 'dict' | optional. dict of values that will be encoded as form data |
| 'json_body' | 'any' | optional. json data to supply as a request. handy for working with JSON-API's |
| 'auth' | 'tuple' | optional. (username,password) tuple for http basic authorization |
| `url` | `string` | url to request |
| `headers` | `dict` | optional. dictionary of headers to add to request |
| `body` | `string` | optional. raw string body to provide to the request |
| `form_body` | `dict` | optional. dict of values that will be encoded as form data |
| `json_body` | `any` | optional. json data to supply as a request. handy for working with JSON-API's |
| `auth` | `tuple` | optional. (username,password) tuple for http basic authorization |
#### def <b>patch</b>
#### def <i>http</i>.<b>patch</b>
```go
patch(url,params={},headers={},body="",form_body={},json_body={},auth=()) response
http.patch(url,params={},headers={},body="",form_body={},json_body={},auth=()) response
```
perform an HTTP PATCH request, returning a response
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'url' | 'string' | url to request |
| 'headers' | 'dict' | optional. dictionary of headers to add to request |
| 'body' | 'string' | optional. raw string body to provide to the request |
| 'form_body' | 'dict' | optional. dict of values that will be encoded as form data |
| 'json_body' | 'any' | optional. json data to supply as a request. handy for working with JSON-API's |
| 'auth' | 'tuple' | optional. (username,password) tuple for http basic authorization |
| `url` | `string` | url to request |
| `headers` | `dict` | optional. dictionary of headers to add to request |
| `body` | `string` | optional. raw string body to provide to the request |
| `form_body` | `dict` | optional. dict of values that will be encoded as form data |
| `json_body` | `any` | optional. json data to supply as a request. handy for working with JSON-API's |
| `auth` | `tuple` | optional. (username,password) tuple for http basic authorization |
#### def <b>post</b>
#### def <i>http</i>.<b>post</b>
```go
post(url,params={},headers={},body="",form_body={},json_body={},auth=()) response
http.post(url,params={},headers={},body="",form_body={},json_body={},auth=()) response
```
perform an HTTP POST request, returning a response
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'url' | 'string' | url to request |
| 'headers' | 'dict' | optional. dictionary of headers to add to request |
| 'body' | 'string' | optional. raw string body to provide to the request |
| 'form_body' | 'dict' | optional. dict of values that will be encoded as form data |
| 'json_body' | 'any' | optional. json data to supply as a request. handy for working with JSON-API's |
| 'auth' | 'tuple' | optional. (username,password) tuple for http basic authorization |
| `url` | `string` | url to request |
| `headers` | `dict` | optional. dictionary of headers to add to request |
| `body` | `string` | optional. raw string body to provide to the request |
| `form_body` | `dict` | optional. dict of values that will be encoded as form data |
| `json_body` | `any` | optional. json data to supply as a request. handy for working with JSON-API's |
| `auth` | `tuple` | optional. (username,password) tuple for http basic authorization |
#### def <b>put</b>
#### def <i>http</i>.<b>put</b>
```go
put(url,params={},headers={},body="",form_body={},json_body={},auth=()) response
http.put(url,params={},headers={},body="",form_body={},json_body={},auth=()) response
```
perform an HTTP PUT request, returning a response
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'url' | 'string' | url to request |
| 'headers' | 'dict' | optional. dictionary of headers to add to request |
| 'body' | 'string' | optional. raw string body to provide to the request |
| 'form_body' | 'dict' | optional. dict of values that will be encoded as form data |
| 'json_body' | 'any' | optional. json data to supply as a request. handy for working with JSON-API's |
| 'auth' | 'tuple' | optional. (username,password) tuple for http basic authorization |
| `url` | `string` | url to request |
| `headers` | `dict` | optional. dictionary of headers to add to request |
| `body` | `string` | optional. raw string body to provide to the request |
| `form_body` | `dict` | optional. dict of values that will be encoded as form data |
| `json_body` | `any` | optional. json data to supply as a request. handy for working with JSON-API's |
| `auth` | `tuple` | optional. (username,password) tuple for http basic authorization |
## Types
### 'response'
### type <b>response</b>
the result of performing a http request
**Fields**
###### Properties
| name | type | description |
|------|------|-------------|
| url | string | the url that was ultimately requested (may change after redirects) |
| status_code | int | response status code (for example: 200 == OK) |
| headers | dict | dictionary of response headers |
| encoding | string | transfer encoding. example: "octet-stream" or "application/json" |
| `url` | `string` | the url that was ultimately requested (may change after redirects) |
| `status_code` | `int` | response status code (for example: 200 == OK) |
| `headers` | `dict` | dictionary of response headers |
| `encoding` | `string` | transfer encoding. example: "octet-stream" or "application/json" |
**Methods**
#### def <b>body</b>
###### Methods
#### def <i>response</i>.<b>body</b>
```go
body() string
response.body() string
```
output response body as a string
#### def <b>json</b>
#### def <i>response</i>.<b>json</b>
```go
json()
response.json()
```
attempt to parse resonse body as json, returning a JSON-decoded result

View File

@ -3,34 +3,42 @@ title: 'encoding/json'
---
json provides functions for working with json data
## Index
* [def <b>dumps</b>(obj) string](#def-ijsonibdumpsb)
* [def <b>loads</b>(source) object](#def-ijsonibloadsb)
## Functions
#### def <b>dumps</b>
#### def <i>json</i>.<b>dumps</b>
```go
dumps(obj) string
json.dumps(obj) string
```
serialize obj to a JSON string
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'obj' | 'object' | input object |
| `obj` | `object` | input object |
#### def <b>loads</b>
#### def <i>json</i>.<b>loads</b>
```go
loads(source) object
json.loads(source) object
```
read a source JSON string to a starlark object
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'source' | 'string' | input string of json data |
| `source` | `string` | input string of json data |

View File

@ -3,161 +3,178 @@ title: 'os'
---
os provides a platform-independent interface to operating system functionality.
## Index
* [def <b>chdir</b>(dir)](#def-iosibchdirb)
* [def <b>getenv</b>(key) dir](#def-iosibgetenvb)
* [def <b>getwd</b>() dir](#def-iosibgetwdb)
* [def <b>mkdir</b>(name, perms=0o777)](#def-iosibmkdirb)
* [def <b>mkdir_all</b>(name, perms=0o777)](#def-iosibmkdir_allb)
* [def <b>read_file</b>(filename) string](#def-iosibread_fileb)
* [def <b>remove</b>(name)](#def-iosibremoveb)
* [def <b>remove_all</b>(path)](#def-iosibremove_allb)
* [def <b>rename</b>(oldpath, newpath)](#def-iosibrenameb)
* [def <b>setenv</b>(key, value) dir](#def-iosibsetenvb)
* [def <b>write_file</b>(filename, data, perms=0o644)](#def-iosibwrite_fileb)
## Functions
#### def <b>chdir</b>
#### def <i>os</i>.<b>chdir</b>
```go
chdir(dir)
os.chdir(dir)
```
changes the current working directory to the named directory.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'dir' | 'string' | target dir |
| `dir` | `string` | target dir |
#### def <b>getenv</b>
#### def <i>os</i>.<b>getenv</b>
```go
getenv(key) dir
os.getenv(key) dir
```
retrieves the value of the environment variable named by the key.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'key' | 'string' | name of the environment variable |
| `key` | `string` | name of the environment variable |
#### def <b>getwd</b>
#### def <i>os</i>.<b>getwd</b>
```go
getwd() dir
os.getwd() dir
```
returns a rooted path name corresponding to the current directory.
#### def <b>mkdir</b>
#### def <i>os</i>.<b>mkdir</b>
```go
mkdir(name, perms=0o777)
os.mkdir(name, perms=0o777)
```
creates a new directory with the specified name and permission bits (before umask).
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'name' | 'string' | name of the folder to be created |
| 'perms' | 'int' | optional, permission of the folder |
| `name` | `string` | name of the folder to be created |
| `perms` | `int` | optional, permission of the folder |
#### def <b>mkdir_all</b>
#### def <i>os</i>.<b>mkdir_all</b>
```go
mkdir_all(name, perms=0o777)
os.mkdir_all(name, perms=0o777)
```
creates a new directory with the specified name and permission bits (before umask).
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'name' | 'string' | name of the folder to be created |
| 'perms' | 'int' | optional, permission of the folder |
| `name` | `string` | name of the folder to be created |
| `perms` | `int` | optional, permission of the folder |
#### def <b>read_file</b>
#### def <i>os</i>.<b>read_file</b>
```go
read_file(filename) string
os.read_file(filename) string
```
reads the file named by filename and returns the contents.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'filename' | 'string' | name of the file to be written |
| 'data' | 'string' | content to be witten to the file |
| 'perms' | 'int' | optional, permission of the file |
| `filename` | `string` | name of the file to be written |
| `data` | `string` | content to be witten to the file |
| `perms` | `int` | optional, permission of the file |
#### def <b>remove</b>
#### def <i>os</i>.<b>remove</b>
```go
remove(name)
os.remove(name)
```
removes the named file or (empty) directory.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'name' | 'string' | name of the file or directory to be deleted |
| `name` | `string` | name of the file or directory to be deleted |
#### def <b>remove_all</b>
#### def <i>os</i>.<b>remove_all</b>
```go
remove_all(path)
os.remove_all(path)
```
removes path and any children it contains. It removes everything it can but returns the first error it encounters.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'name' | 'string' | path to be deleted |
| `name` | `string` | path to be deleted |
#### def <b>rename</b>
#### def <i>os</i>.<b>rename</b>
```go
rename(oldpath, newpath)
os.rename(oldpath, newpath)
```
renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it. OS-specific restrictions may apply when oldpath and newpath are in different directories.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'oldpath' | 'string' | old path |
| 'newpath' | 'string' | new path |
| `oldpath` | `string` | old path |
| `newpath` | `string` | new path |
#### def <b>setenv</b>
#### def <i>os</i>.<b>setenv</b>
```go
setenv(key, value) dir
os.setenv(key, value) dir
```
sets the value of the environment variable named by the key.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'key' | 'string' | name of the environment variable |
| 'value' | 'string' | value of the environment variable |
| `key` | `string` | name of the environment variable |
| `value` | `string` | value of the environment variable |
#### def <b>write_file</b>
#### def <i>os</i>.<b>write_file</b>
```go
write_file(filename, data, perms=0o644)
os.write_file(filename, data, perms=0o644)
```
retrieves the value of the environment variable named by the key.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'filename' | 'string' | name of the file to be written |
| 'data' | 'string' | content to be witten to the file |
| 'perms' | 'int' | optional, permission of the file |
| `filename` | `string` | name of the file to be written |
| `data` | `string` | content to be witten to the file |
| `perms` | `int` | optional, permission of the file |

View File

@ -1,59 +1,68 @@
---
title: 're'
title: ''
---
re defines regular expression functions, it's intended to be a drop-in subset of python's re module for starlark: https://docs.python.org/3/library/re.html
## Index
* [def <b>findall</b>(pattern, text, flags=0)](#def-ireibfindallb)
* [def <b>split</b>(pattern, text, maxsplit=0, flags=0)](#def-ireibsplitb)
* [def <b>sub</b>(pattern, repl, text, count=0, flags=0)](#def-ireibsubb)
## Functions
#### def <b>findall</b>
#### def <i>re</i>.<b>findall</b>
```go
findall(pattern, text, flags=0)
re.findall(pattern, text, flags=0)
```
Returns all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'pattern' | 'string' | regular expression pattern string |
| 'text' | 'string' | string to find within |
| 'flags' | 'int' | integer flags to control regex behaviour. reserved for future use |
| `pattern` | `string` | regular expression pattern string |
| `text` | `string` | string to find within |
| `flags` | `int` | integer flags to control regex behaviour. reserved for future use |
#### def <b>split</b>
#### def <i>re</i>.<b>split</b>
```go
split(pattern, text, maxsplit=0, flags=0)
re.split(pattern, text, maxsplit=0, flags=0)
```
Split text by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'pattern' | 'string' | regular expression pattern string |
| 'text' | 'string' | input string to split |
| 'maxsplit' | 'int' | maximum number of splits to make. default 0 splits all matches |
| 'flags' | 'int' | integer flags to control regex behaviour. reserved for future use |
| `pattern` | `string` | regular expression pattern string |
| `text` | `string` | input string to split |
| `maxsplit` | `int` | maximum number of splits to make. default 0 splits all matches |
| `flags` | `int` | integer flags to control regex behaviour. reserved for future use |
#### def <b>sub</b>
#### def <i>re</i>.<b>sub</b>
```go
sub(pattern, repl, text, count=0, flags=0)
re.sub(pattern, repl, text, count=0, flags=0)
```
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isnt found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth.
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'pattern' | 'string' | regular expression pattern string |
| 'repl' | 'string' | string to replace matches with |
| 'text' | 'string' | input string to replace |
| 'count' | 'int' | number of replacements to make, default 0 means replace all matches |
| 'flags' | 'int' | integer flags to control regex behaviour. reserved for future use |
| `pattern` | `string` | regular expression pattern string |
| `repl` | `string` | string to replace matches with |
| `text` | `string` | input string to replace |
| `count` | `int` | number of replacements to make, default 0 means replace all matches |
| `flags` | `int` | integer flags to control regex behaviour. reserved for future use |

View File

@ -3,34 +3,42 @@ title: 'encoding/yaml'
---
yaml provides functions for working with yaml data
## Index
* [def <b>dumps</b>(obj) string](#def-iyamlibdumpsb)
* [def <b>loads</b>(source) object](#def-iyamlibloadsb)
## Functions
#### def <b>dumps</b>
#### def <i>yaml</i>.<b>dumps</b>
```go
dumps(obj) string
yaml.dumps(obj) string
```
serialize obj to a yaml string
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'obj' | 'object' | input object |
| `obj` | `object` | input object |
#### def <b>loads</b>
#### def <i>yaml</i>.<b>loads</b>
```go
loads(source) object
yaml.loads(source) object
```
read a source yaml string to a starlark object
**parameters:**
###### Arguments
| name | type | description |
|------|------|-------------|
| 'source' | 'string' | input string of yaml data |
| `source` | `string` | input string of yaml data |

View File

@ -101,6 +101,8 @@ title: '{{ .Path }}'
| `{{ .Name }}` | `{{ .Type }}` | {{ .Description }} |
{{ end -}}
{{ end }}
{{ if gt (len .Examples) 0 }}
###### Examples
{{ range .Examples -}}
@ -109,7 +111,6 @@ title: '{{ .Path }}'
{{ .Code }}
```
{{ end -}}
{{ end -}}
{{ end -}}

1
go.mod
View File

@ -13,6 +13,7 @@ require (
github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e // indirect
github.com/hashicorp/go-hclog v0.11.0
github.com/hashicorp/go-plugin v1.0.1-0.20190610192547-a1bc61569a26
github.com/hashicorp/go-version v1.2.0
github.com/hashicorp/hcl2 v0.0.0-20190618163856-0b64543c968c
github.com/hashicorp/terraform v0.12.23
github.com/jessevdk/go-flags v1.4.0

View File

@ -180,9 +180,14 @@ func (b *Backend) state(
}
// String honors the starlark.Value interface.
func (b *Backend) String() string {
return fmt.Sprintf("Backend<%s>", b.typ)
}
// Type honors the starlark.Value interface.
func (b *Backend) Type() string {
return fmt.Sprintf("Backend<%s>", b.typ)
return "Backend"
}
// State represents a Terraform state read by a backend.

View File

@ -49,14 +49,23 @@ func (c *ResourceCollection) LoadList(l *starlark.List) error {
return nil
}
// Path returns the path of the ResourceCollection.
func (c *ResourceCollection) Path() string {
if c.parent != nil && c.parent.kind != ProviderKind {
return fmt.Sprintf("%s.%s", c.parent.Path(), c.typ)
}
return fmt.Sprintf("%s.%s.%s", c.provider.typ, c.kind, c.typ)
}
// String honors the starlark.Value interface.
func (c *ResourceCollection) String() string {
return fmt.Sprintf("%s", c.typ)
return fmt.Sprintf("ResourceCollection<%s>", c.Path())
}
// Type honors the starlark.Value interface.
func (c *ResourceCollection) Type() string {
return fmt.Sprintf("ResourceCollection<%s.%s>", c.kind, c.typ)
return "ResourceCollection"
}
// Truth honors the starlark.Value interface.

View File

@ -89,7 +89,7 @@ func (s *Backend) ToHCL(b *hclwrite.Body) {
b.AppendNewline()
}
func (t *MapSchema) ToHCL(b *hclwrite.Body) {
func (t *ResourceCollectionGroup) ToHCL(b *hclwrite.Body) {
names := make(sort.StringSlice, len(t.collections))
var i int
for name := range t.collections {

View File

@ -77,7 +77,7 @@ func BuiltinProvider(pm *terraform.PluginManager) starlark.Value {
// the name is auto-generated following the partern `id_%s`. At
// Terraform is called [`alias`](https://www.terraform.io/docs/configuration/providers.html#alias-multiple-provider-instances)
// __dict__ Dict
// A dictionary containing all the values of the resource.
// A dictionary containing all set arguments and blocks of the provider.
// data MapSchema
// Data sources defined by the provider.
// resource MapSchema
@ -93,8 +93,8 @@ type Provider struct {
provider *plugin.GRPCProvider
meta discovery.PluginMeta
dataSources *MapSchema
resources *MapSchema
dataSources *ResourceCollectionGroup
resources *ResourceCollectionGroup
*Resource
}
@ -130,19 +130,19 @@ func MakeProvider(pm *terraform.PluginManager, typ, version, name string) (*Prov
}
p.Resource = MakeResource(name, typ, ProviderKind, response.Provider.Block, p, nil)
p.dataSources = NewMapSchema(p, typ, DataSourceKind, response.DataSources)
p.resources = NewMapSchema(p, typ, ResourceKind, response.ResourceTypes)
p.dataSources = NewResourceCollectionGroup(p, DataSourceKind, response.DataSources)
p.resources = NewResourceCollectionGroup(p, ResourceKind, response.ResourceTypes)
return p, nil
}
func (p *Provider) String() string {
return fmt.Sprintf("provider(%q)", p.typ)
return fmt.Sprintf("Provider<%s>", p.typ)
}
// Type honors the starlark.Value interface. It shadows p.Resource.Type.
func (p *Provider) Type() string {
return fmt.Sprintf("Provider<%s>", p.typ)
return "Provider"
}
// Attr honors the starlark.Attr interface.
@ -177,54 +177,55 @@ func (x *Provider) CompareSameType(op syntax.Token, y_ starlark.Value, depth int
}
}
type MapSchema struct {
p *Provider
prefix string
type ResourceCollectionGroup struct {
provider *Provider
kind Kind
schemas map[string]providers.Schema
collections map[string]*ResourceCollection
}
func NewMapSchema(p *Provider, prefix string, k Kind, schemas map[string]providers.Schema) *MapSchema {
return &MapSchema{
p: p,
prefix: prefix,
func NewResourceCollectionGroup(p *Provider, k Kind, schemas map[string]providers.Schema) *ResourceCollectionGroup {
return &ResourceCollectionGroup{
provider: p,
kind: k,
schemas: schemas,
collections: make(map[string]*ResourceCollection),
}
}
func (m *MapSchema) String() string {
return fmt.Sprintf("schemas(%q)", m.prefix)
// Path returns the path of the ResourceCollectionGroup.
func (r *ResourceCollectionGroup) Path() string {
return fmt.Sprintf("%s.%s", r.provider.typ, r.kind)
}
func (m *MapSchema) Type() string {
return "schemas"
func (r *ResourceCollectionGroup) String() string {
return fmt.Sprintf("ResourceCollectionGroup<%s>", r.Path())
}
func (m *MapSchema) Freeze() {}
func (m *MapSchema) Truth() starlark.Bool { return true }
func (m *MapSchema) Hash() (uint32, error) { return 1, nil }
func (m *MapSchema) Name() string { return m.prefix }
func (r *ResourceCollectionGroup) Type() string {
return "ResourceCollectionGroup"
}
func (m *MapSchema) Attr(name string) (starlark.Value, error) {
name = m.prefix + "_" + name
func (m *ResourceCollectionGroup) Freeze() {}
func (m *ResourceCollectionGroup) Truth() starlark.Bool { return true }
func (m *ResourceCollectionGroup) Hash() (uint32, error) { return 1, nil }
func (m *ResourceCollectionGroup) Attr(name string) (starlark.Value, error) {
name = m.provider.typ + "_" + name
if c, ok := m.collections[name]; ok {
return c, nil
}
if schema, ok := m.schemas[name]; ok {
m.collections[name] = NewResourceCollection(name, m.kind, schema.Block, m.p, m.p.Resource)
m.collections[name] = NewResourceCollection(name, m.kind, schema.Block, m.provider, m.provider.Resource)
return m.collections[name], nil
}
return starlark.None, nil
}
func (s *MapSchema) AttrNames() []string {
func (s *ResourceCollectionGroup) AttrNames() []string {
names := make([]string, len(s.schemas))
var i int

View File

@ -68,5 +68,9 @@ func MakeProvisioner(pm *terraform.PluginManager, typ string) (*Provisioner, err
// Type honors the starlark.Value interface. It shadows p.Resource.Type.
func (p *Provisioner) Type() string {
return "Provisioner"
}
func (p *Provisioner) String() string {
return fmt.Sprintf("Provisioner<%s>", p.typ)
}

View File

@ -83,7 +83,7 @@ const (
// the name is auto-generated following the partern `id_%s`. Nested kind
// resources are unamed.
// __dict__ Dict
// A dictionary containing all the values of the resource.
// A dictionary containing all set arguments and blocks of the resource.
// <argument> <scalar>/Computed
// Arguments defined by the resource schema, thus can be of any
// scalar type or Computed values.
@ -167,12 +167,21 @@ func (r *Resource) loadKeywordArgs(kwargs []starlark.Tuple) error {
// String honors the starlark.Value interface.
func (r *Resource) String() string {
return fmt.Sprintf("%s(%q)", r.kind, r.typ)
return fmt.Sprintf("Resource<%s>", r.Path())
}
// Path returns the path of the Resource.
func (r *Resource) Path() string {
if r.parent != nil && r.parent.kind != ProviderKind {
return fmt.Sprintf("%s.%s", r.parent.Path(), r.typ)
}
return fmt.Sprintf("%s.%s.%s", r.provider.typ, r.kind, r.typ)
}
// Type honors the starlark.Value interface.
func (r *Resource) Type() string {
return fmt.Sprintf("Resource<%s.%s>", r.kind, r.typ)
return fmt.Sprintf("Resource<%s>", r.kind)
}
// Truth honors the starlark.Value interface.
@ -308,12 +317,12 @@ func (r *Resource) doSetField(name string, v starlark.Value, allowComputed bool)
attr, ok := r.block.Attributes[name]
if !ok {
errmsg := fmt.Sprintf("%s has no .%s field or method", r.typ, name)
errmsg := fmt.Sprintf("%s has no .%s field or method", r, name)
return starlark.NoSuchAttrError(errmsg)
}
if attr.Computed && !attr.Optional && !allowComputed {
return fmt.Errorf("%s: can't set computed %s attribute", r.typ, name)
return fmt.Errorf("%s: can't set computed %s attribute", r, name)
}
if err := MustTypeFromCty(attr.Type).Validate(v); err != nil {
@ -380,7 +389,7 @@ func (r *Resource) dependsOn(_ *starlark.Thread, _ *starlark.Builtin, args starl
for i, arg := range args {
resource, ok := arg.(*Resource)
if !ok || resource.kind != DataSourceKind && resource.kind != ResourceKind {
return nil, fmt.Errorf("expected Resource<[data|resource].*>, got %s", arg.Type())
return nil, fmt.Errorf("expected Resource<[data|resource]>, got %s", arg.Type())
}
if r == resource {
@ -399,7 +408,7 @@ func (r *Resource) addProvisioner(_ *starlark.Thread, _ *starlark.Builtin, args
for i, arg := range args {
provisioner, ok := arg.(*Provisioner)
if !ok {
return nil, fmt.Errorf("expected Provisioner<*>, got %s", arg.Type())
return nil, fmt.Errorf("expected Provisioner, got %s", arg.Type())
}
provisioners[i] = provisioner

View File

@ -5,7 +5,8 @@ b = backend("gcs")
# resource
assert.eq(b.__kind__, "backend")
assert.eq(b.__type__, "gcs")
assert.eq(type(b), "Backend<gcs>")
assert.eq(type(b), "Backend")
assert.eq(str(b), "Backend<gcs>")
# attr
b.bucket = "tf-state-prod"

View File

@ -1,12 +1,17 @@
def print_provider_stats(p):
def print_provider_info(p):
print("Provider %s[%s] (%s)" % (p.__type__, p.__name__, p.__version__))
print(" Defines Data Sources: %d" % len(dir(p.data)))
print(" Defines Resources: %d" % len(dir(p.resource)))
print(" Configuration: %s" % p.__dict__)
provider = tf.provider("aws", "2.13.0")
print_provider_stats(provider)
provider = tf.provider("google")
provider.project = "acme-app"
provider.region = "us-central1"
print_provider_info(provider)
# Output:
# Provider aws[id_1] (2.13.0)
# Defines Data Sources: 131
# Defines Resources: 506
# Provider google[id_1] (3.13.0)
# Defines Data Sources: 58
# Defines Resources: 261
# Configuration: {"project": "acme-app", "region": "us-central1"}

View File

@ -3,11 +3,11 @@ load("assert.star", "assert")
p = tf.provider("aws", "2.13.0")
d = p.data.ami()
assert.eq(type(d.filter), "ResourceCollection<nested.filter>")
assert.eq(type(d.filter), "ResourceCollection")
bar = d.filter(name="bar", values=["qux"])
assert.eq(type(bar), "Resource<nested.filter>")
assert.eq(str(bar), "Resource<aws.data.aws_ami.filter>")
assert.eq(bar.name, "bar")
assert.eq(bar.values, ["qux"])

View File

@ -20,11 +20,22 @@ assert.eq(len(dir(p.resource)), 506)
resources = dir(p.resource)
assert.contains(resources, "instance")
assert.eq(type(p), "Provider<aws>")
assert.eq(type(p.resource.instance), "ResourceCollection<resource.aws_instance>")
assert.eq(type(p.resource.instance()), "Resource<resource.aws_instance>")
p.resource.instance()
# types
assert.eq(type(p), "Provider")
assert.eq(type(p.resource), "ResourceCollectionGroup")
assert.eq(type(p.resource.instance), "ResourceCollection")
assert.eq(type(p.resource.instance()), "Resource<resource>")
assert.eq(type(p.data.ami().filter()), "Resource<nested>")
# string
assert.eq(str(p), "Provider<aws>")
assert.eq(str(p.resource), "ResourceCollectionGroup<aws.resource>")
assert.eq(str(p.resource.instance), "ResourceCollection<aws.resource.aws_instance>")
assert.eq(str(p.resource.instance()), "Resource<aws.resource.aws_instance>")
assert.eq(str(p.data.ami().filter()), "Resource<aws.data.aws_ami.filter>")
assert.eq(len(p.resource.instance), 2)
p.region = "us-west-2"

View File

@ -29,4 +29,5 @@ assert.eq(hcl(file), "" +
# type
assert.eq(type(file), "Provisioner<file>")
assert.eq(type(file), "Provisioner")
assert.eq(str(file), "Provisioner<file>")

View File

@ -26,7 +26,7 @@ assert.eq("__dict__" in dir(qux), True)
assert.eq(qux.name, None)
# attr not-exists
assert.fails(lambda: qux.foo, "Resource<data.ignition_user> has no .foo field or method")
assert.fails(lambda: qux.foo, "Resource<data> has no .foo field or method")
# attr id
assert.eq(type(qux.id), "Computed<string>")
@ -35,7 +35,7 @@ aws = tf.provider("aws", "2.13.0")
# attr output assignation
def invalidOutput(): aws.data.instance().public_dns = "foo"
assert.fails(invalidOutput, "aws_instance: can't set computed public_dns attribute")
assert.fails(invalidOutput, "Resource<aws.data.aws_instance>: can't set computed public_dns attribute")
# attr output in asignation
@ -165,7 +165,7 @@ user.uid = 42
user.groups = ["foo", "bar"]
user.system = True
assert.eq(type(user), "Resource<data.ignition_user>")
assert.eq(str(user), "Resource<ignition.data.ignition_user>")
assert.eq(user.__dict__, {
"name": "foo",
"uid": 42,
@ -204,10 +204,10 @@ instanceB = aws.resource.instance()
instanceA.depends_on(instanceB)
def dependsOnNonResource(): instanceA.depends_on(42)
assert.fails(dependsOnNonResource, "expected Resource<\\[data|resource\\].\\*>, got int")
assert.fails(dependsOnNonResource, "expected Resource<\\[data|resource\\]>, got int")
def dependsOnNestedResource(): instanceA.depends_on(disk.partition())
assert.fails(dependsOnNestedResource, "expected Resource<\\[data|resource\\].\\*>, got Resource<nested.partition>")
assert.fails(dependsOnNestedResource, "expected Resource<\\[data|resource\\]>, got Resource<nested.partition>")
def dependsOnItself(): instanceA.depends_on(instanceA)
assert.fails(dependsOnItself, "can't depend on itself")

View File

@ -1,6 +1,7 @@
load("assert.star", "assert")
b = backend("local")
b.path = "fixtures/modules/terraform.tfstate"
s = b.state()

View File

@ -25,11 +25,11 @@ assert.eq(tf.backend, None)
tf.backend = backend("local")
tf.backend.path = "foo"
assert.eq(type(tf.backend), "Backend<local>")
assert.eq(str(tf.backend), "Backend<local>")
def backendWrongType(): tf.backend = "foo"
assert.fails(backendWrongType, "unexpected value string at backend")
assert.eq(type(tf.backend), "Backend<local>")
assert.eq(str(tf.backend), "Backend<local>")
# pop provider
baz = tf.provider("aws", "2.13.0", "baz", region="baz")