1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

vfmt: change all '$expr' to '${expr}' (#16428)

This commit is contained in:
yuyi
2022-11-15 21:53:13 +08:00
committed by GitHub
parent 56239b4a23
commit 017ace6ea7
859 changed files with 7156 additions and 7135 deletions

View File

@@ -70,7 +70,7 @@ fn (am AssetManager) combine(asset_type string, to_file bool) string {
panic('vweb.assets: you must set a cache dir.')
}
cache_key := am.get_cache_key(asset_type)
out_file := '$am.cache_dir/${cache_key}.$asset_type'
out_file := '${am.cache_dir}/${cache_key}.${asset_type}'
mut out := ''
// use cache
if os.exists(out_file) {
@@ -114,7 +114,7 @@ fn (am AssetManager) get_cache_key(asset_type string) string {
}
}
hash := md5.sum(files_salt.bytes()).hex()
return '$hash-$latest_modified'
return '${hash}-${latest_modified}'
}
fn (am AssetManager) include(asset_type string, combine bool) string {
@@ -123,19 +123,19 @@ fn (am AssetManager) include(asset_type string, combine bool) string {
if asset_type == 'css' {
if combine {
file := am.combine(asset_type, true)
return '<link rel="stylesheet" href="$file">\n'
return '<link rel="stylesheet" href="${file}">\n'
}
for asset in assets {
out += '<link rel="stylesheet" href="$asset.file_path">\n'
out += '<link rel="stylesheet" href="${asset.file_path}">\n'
}
}
if asset_type == 'js' {
if combine {
file := am.combine(asset_type, true)
return '<script type="text/javascript" src="$file"></script>\n'
return '<script type="text/javascript" src="${file}"></script>\n'
}
for asset in assets {
out += '<script type="text/javascript" src="$asset.file_path"></script>\n'
out += '<script type="text/javascript" src="${asset.file_path}"></script>\n'
}
}
return out
@@ -159,7 +159,7 @@ fn (mut am AssetManager) add(asset_type string, file string) bool {
} else if asset_type == 'js' {
am.js << asset
} else {
panic('$assets.unknown_asset_type_error ($asset_type).')
panic('${assets.unknown_asset_type_error} (${asset_type}).')
}
return true
}
@@ -176,7 +176,7 @@ fn (am AssetManager) exists(asset_type string, file string) bool {
fn (am AssetManager) get_assets(asset_type string) []Asset {
if asset_type != 'css' && asset_type != 'js' {
panic('$assets.unknown_asset_type_error ($asset_type).')
panic('${assets.unknown_asset_type_error} (${asset_type}).')
}
assets := if asset_type == 'css' { am.css } else { am.js }
return assets

View File

@@ -124,7 +124,7 @@ fn test_include_css() {
mut am := assets.new_manager()
file1 := get_test_file_path('test1.css')
am.add_css(file1)
expected := '<link rel="stylesheet" href="$file1">\n'
expected := '<link rel="stylesheet" href="${file1}">\n'
actual := am.include_css(false)
assert actual == expected
assert actual.contains(expected)
@@ -133,7 +133,7 @@ fn test_include_css() {
am.add_css(file2)
am.cache_dir = cache_dir('test_include_css')
clean_cache_dir(am.cache_dir)
expected2 := expected + '<link rel="stylesheet" href="$file2">\n'
expected2 := expected + '<link rel="stylesheet" href="${file2}">\n'
actual2 := am.include_css(false)
assert actual2 == expected2
assert actual2.contains(expected2)
@@ -141,7 +141,7 @@ fn test_include_css() {
clean_cache_dir(am.cache_dir)
actual3 := am.include_css(true)
assert actual3.contains(expected2) == false
assert actual3.starts_with('<link rel="stylesheet" href="$am.cache_dir/') == true
assert actual3.starts_with('<link rel="stylesheet" href="${am.cache_dir}/') == true
// Test cache path doesn't change when input files and minify setting do not.
clean_cache_dir(am.cache_dir)
actual4 := am.include_css(true)
@@ -153,7 +153,7 @@ fn test_include_js() {
mut am := assets.new_manager()
file1 := get_test_file_path('test1.js')
am.add_js(file1)
expected := '<script type="text/javascript" src="$file1"></script>\n'
expected := '<script type="text/javascript" src="${file1}"></script>\n'
actual := am.include_js(false)
assert actual == expected
assert actual.contains(expected)
@@ -162,7 +162,7 @@ fn test_include_js() {
am.add_js(file2)
am.cache_dir = cache_dir('test_include_js')
clean_cache_dir(am.cache_dir)
expected2 := expected + '<script type="text/javascript" src="$file2"></script>\n'
expected2 := expected + '<script type="text/javascript" src="${file2}"></script>\n'
actual2 := am.include_js(false)
assert actual2 == expected2
assert actual2.contains(expected2)
@@ -170,7 +170,7 @@ fn test_include_js() {
clean_cache_dir(am.cache_dir)
actual3 := am.include_js(true)
assert actual3.contains(expected2) == false
assert actual3.starts_with('<script type="text/javascript" src="$am.cache_dir/')
assert actual3.starts_with('<script type="text/javascript" src="${am.cache_dir}/')
// Test cache path doesn't change when input files and minify setting do not.
clean_cache_dir(am.cache_dir)
actual4 := am.include_js(true)

View File

@@ -25,7 +25,7 @@ fn generate() string {
mut out := ''
for _ in 0 .. 42 {
i := rand.intn(csrf.chars.len_utf8()) or {
panic('Error while trying to generate Csrf-Token: $err')
panic('Error while trying to generate Csrf-Token: ${err}')
}
out = out + csrf.chars[i..i + 1]
}

View File

@@ -15,13 +15,13 @@ fn (mut app App) index() vweb.Result {
app.set_csrf_cookie(csrf.HttpOnly{false})
// Get the token-value from the csrf-cookie that was just setted
token := app.get_csrf_token() or { panic(err) }
return app.text("Csrf-Token set! It's value is: $token")
return app.text("Csrf-Token set! It's value is: ${token}")
}
fn test_send_a_request_to_homepage_expecting_a_csrf_cookie() {
spawn vweb.run_at(&App{}, vweb.RunParams{ port: sport })
time.sleep(500 * time.millisecond)
res := http.get('http://localhost:$sport/')?
res := http.get('http://localhost:${sport}/')?
if res.header.str().contains('__Host-Csrf-Token') {
assert true
} else {

View File

@@ -6,7 +6,7 @@ import net.http
// Parsing function attributes for methods and path.
fn parse_attrs(name string, attrs []string) !([]http.Method, string) {
if attrs.len == 0 {
return [http.Method.get], '/$name'
return [http.Method.get], '/${name}'
}
mut x := attrs.clone()
@@ -41,7 +41,7 @@ fn parse_attrs(name string, attrs []string) !([]http.Method, string) {
methods = [http.Method.get]
}
if path == '' {
path = '/$name'
path = '/${name}'
}
// Make path lowercase for case-insensitive comparisons
return methods, path.to_lower()

View File

@@ -12,16 +12,16 @@ fn (rp RoutePair) test() ?[]string {
}
fn (rp RoutePair) test_match() {
rp.test() or { panic('should match: $rp') }
rp.test() or { panic('should match: ${rp}') }
}
fn (rp RoutePair) test_no_match() {
rp.test() or { return }
panic('should not match: $rp')
panic('should not match: ${rp}')
}
fn (rp RoutePair) test_param(expected []string) {
res := rp.test() or { panic('should match: $rp') }
res := rp.test() or { panic('should match: ${rp}') }
assert res == expected
}

View File

@@ -50,7 +50,7 @@ pub fn (mut sse SSEConnection) start() ! {
start_sb.write_string('\r\nCache-Control: no-cache')
start_sb.write_string('\r\nContent-Type: text/event-stream')
for k, v in sse.headers {
start_sb.write_string('\r\n$k: $v')
start_sb.write_string('\r\n${k}: ${v}')
}
start_sb.write_string('\r\n')
sse.conn.write(start_sb) or { return error('could not start sse response') }
@@ -61,16 +61,16 @@ pub fn (mut sse SSEConnection) start() ! {
pub fn (mut sse SSEConnection) send_message(message SSEMessage) ! {
mut sb := strings.new_builder(512)
if message.id != '' {
sb.write_string('id: $message.id\n')
sb.write_string('id: ${message.id}\n')
}
if message.event != '' {
sb.write_string('event: $message.event\n')
sb.write_string('event: ${message.event}\n')
}
if message.data != '' {
sb.write_string('data: $message.data\n')
sb.write_string('data: ${message.data}\n')
}
if message.retry != 0 {
sb.write_string('retry: $message.retry\n')
sb.write_string('retry: ${message.retry}\n')
}
sb.write_string('\n')
sse.conn.write(sb)!

View File

@@ -7,7 +7,7 @@ import io
const (
sport = 12380
localserver = 'localhost:$sport'
localserver = 'localhost:${sport}'
exit_after_time = 12000 // milliseconds
vexe = os.getenv('VEXE')
vweb_logfile = os.getenv('VWEB_LOGFILE')
@@ -41,9 +41,9 @@ fn test_a_simple_vweb_app_runs_in_the_background() {
if vweb_logfile != '' {
suffix = ' 2>> ${os.quoted_path(vweb_logfile)} >> ${os.quoted_path(vweb_logfile)} &'
}
server_exec_cmd := '${os.quoted_path(serverexe)} $sport $exit_after_time $suffix'
server_exec_cmd := '${os.quoted_path(serverexe)} ${sport} ${exit_after_time} ${suffix}'
$if debug_net_socket_client ? {
eprintln('running:\n$server_exec_cmd')
eprintln('running:\n${server_exec_cmd}')
}
$if windows {
spawn os.system(server_exec_cmd)
@@ -117,7 +117,7 @@ fn assert_common_http_headers(x http.Response) ! {
}
fn test_http_client_index() {
x := http.get('http://$localserver/') or { panic(err) }
x := http.get('http://${localserver}/') or { panic(err) }
assert_common_http_headers(x)!
assert x.header.get(.content_type)! == 'text/plain'
assert x.body == 'Welcome to VWeb'
@@ -125,9 +125,9 @@ fn test_http_client_index() {
fn test_http_client_404() {
url_404_list := [
'http://$localserver/zxcnbnm',
'http://$localserver/JHKAJA',
'http://$localserver/unknown',
'http://${localserver}/zxcnbnm',
'http://${localserver}/JHKAJA',
'http://${localserver}/unknown',
]
for url in url_404_list {
res := http.get(url) or { panic(err) }
@@ -136,39 +136,39 @@ fn test_http_client_404() {
}
fn test_http_client_simple() {
x := http.get('http://$localserver/simple') or { panic(err) }
x := http.get('http://${localserver}/simple') or { panic(err) }
assert_common_http_headers(x)!
assert x.header.get(.content_type)! == 'text/plain'
assert x.body == 'A simple result'
}
fn test_http_client_html_page() {
x := http.get('http://$localserver/html_page') or { panic(err) }
x := http.get('http://${localserver}/html_page') or { panic(err) }
assert_common_http_headers(x)!
assert x.header.get(.content_type)! == 'text/html'
assert x.body == '<h1>ok</h1>'
}
fn test_http_client_settings_page() {
x := http.get('http://$localserver/bilbo/settings') or { panic(err) }
x := http.get('http://${localserver}/bilbo/settings') or { panic(err) }
assert_common_http_headers(x)!
assert x.body == 'username: bilbo'
//
y := http.get('http://$localserver/kent/settings') or { panic(err) }
y := http.get('http://${localserver}/kent/settings') or { panic(err) }
assert_common_http_headers(y)!
assert y.body == 'username: kent'
}
fn test_http_client_user_repo_settings_page() {
x := http.get('http://$localserver/bilbo/gostamp/settings') or { panic(err) }
x := http.get('http://${localserver}/bilbo/gostamp/settings') or { panic(err) }
assert_common_http_headers(x)!
assert x.body == 'username: bilbo | repository: gostamp'
//
y := http.get('http://$localserver/kent/golang/settings') or { panic(err) }
y := http.get('http://${localserver}/kent/golang/settings') or { panic(err) }
assert_common_http_headers(y)!
assert y.body == 'username: kent | repository: golang'
//
z := http.get('http://$localserver/missing/golang/settings') or { panic(err) }
z := http.get('http://${localserver}/missing/golang/settings') or { panic(err) }
assert z.status() == .not_found
}
@@ -183,38 +183,38 @@ fn test_http_client_json_post() {
age: 123
}
json_for_ouser := json.encode(ouser)
mut x := http.post_json('http://$localserver/json_echo', json_for_ouser) or { panic(err) }
mut x := http.post_json('http://${localserver}/json_echo', json_for_ouser) or { panic(err) }
$if debug_net_socket_client ? {
eprintln('/json_echo endpoint response: $x')
eprintln('/json_echo endpoint response: ${x}')
}
assert x.header.get(.content_type)! == 'application/json'
assert x.body == json_for_ouser
nuser := json.decode(User, x.body) or { User{} }
assert '$ouser' == '$nuser'
assert '${ouser}' == '${nuser}'
//
x = http.post_json('http://$localserver/json', json_for_ouser) or { panic(err) }
x = http.post_json('http://${localserver}/json', json_for_ouser) or { panic(err) }
$if debug_net_socket_client ? {
eprintln('/json endpoint response: $x')
eprintln('/json endpoint response: ${x}')
}
assert x.header.get(.content_type)! == 'application/json'
assert x.body == json_for_ouser
nuser2 := json.decode(User, x.body) or { User{} }
assert '$ouser' == '$nuser2'
assert '${ouser}' == '${nuser2}'
}
fn test_http_client_multipart_form_data() {
boundary := '6844a625b1f0b299'
name := 'foo'
ct := 'multipart/form-data; boundary=$boundary'
ct := 'multipart/form-data; boundary=${boundary}'
contents := 'baz buzz'
data := '--$boundary\r
Content-Disposition: form-data; name="$name"\r
data := '--${boundary}\r
Content-Disposition: form-data; name="${name}"\r
\r
$contents\r
--$boundary--\r
${contents}\r
--${boundary}--\r
'
mut x := http.fetch(
url: 'http://$localserver/form_echo'
url: 'http://${localserver}/form_echo'
method: .post
header: http.new_header(
key: .content_type
@@ -223,13 +223,13 @@ $contents\r
data: data
)!
$if debug_net_socket_client ? {
eprintln('/form_echo endpoint response: $x')
eprintln('/form_echo endpoint response: ${x}')
}
assert x.body == contents
}
fn test_http_client_shutdown_does_not_work_without_a_cookie() {
x := http.get('http://$localserver/shutdown') or {
x := http.get('http://${localserver}/shutdown') or {
assert err.msg() == ''
return
}
@@ -241,7 +241,7 @@ fn testsuite_end() {
// This test is guaranteed to be called last.
// It sends a request to the server to shutdown.
x := http.fetch(
url: 'http://$localserver/shutdown'
url: 'http://${localserver}/shutdown'
method: .get
cookies: {
'skey': 'superman'
@@ -269,7 +269,7 @@ fn simple_tcp_client(config SimpleTcpClientConfig) !string {
mut tries := 0
for tries < config.retries {
tries++
eprintln('> client retries: $tries')
eprintln('> client retries: ${tries}')
client = net.dial_tcp(localserver) or {
if tries > config.retries {
return err
@@ -280,7 +280,7 @@ fn simple_tcp_client(config SimpleTcpClientConfig) !string {
break
}
if client == unsafe { nil } {
eprintln('coult not create a tcp client connection to $localserver after $config.retries retries')
eprintln('coult not create a tcp client connection to ${localserver} after ${config.retries} retries')
exit(1)
}
client.set_read_timeout(tcp_r_timeout)
@@ -288,19 +288,19 @@ fn simple_tcp_client(config SimpleTcpClientConfig) !string {
defer {
client.close() or {}
}
message := 'GET $config.path HTTP/1.1
Host: $config.host
User-Agent: $config.agent
message := 'GET ${config.path} HTTP/1.1
Host: ${config.host}
User-Agent: ${config.agent}
Accept: */*
$config.headers
$config.content'
${config.headers}
${config.content}'
$if debug_net_socket_client ? {
eprintln('sending:\n$message')
eprintln('sending:\n${message}')
}
client.write(message.bytes())!
read := io.read_all(reader: client)!
$if debug_net_socket_client ? {
eprintln('received:\n$read')
eprintln('received:\n${read}')
}
return read.bytestr()
}

View File

@@ -21,7 +21,7 @@ struct Config {
fn exit_after_timeout(timeout_in_ms int) {
time.sleep(timeout_in_ms * time.millisecond)
println('>> webserver: pid: $os.getpid(), exiting ...')
println('>> webserver: pid: ${os.getpid()}, exiting ...')
exit(0)
}
@@ -43,7 +43,7 @@ fn main() {
timeout: timeout
global_config: config
}
eprintln('>> webserver: pid: $os.getpid(), started on http://localhost:$app.port/ , with maximum runtime of $app.timeout milliseconds.')
eprintln('>> webserver: pid: ${os.getpid()}, started on http://localhost:${app.port}/ , with maximum runtime of ${app.timeout} milliseconds.')
vweb.run_at(app, host: 'localhost', port: http_port, family: .ip)!
}
@@ -71,7 +71,7 @@ pub fn (mut app App) settings(username string) vweb.Result {
if username !in known_users {
return app.not_found()
}
return app.html('username: $username')
return app.html('username: ${username}')
}
['/:user/:repo/settings']
@@ -79,7 +79,7 @@ pub fn (mut app App) user_repo_settings(username string, repository string) vweb
if username !in known_users {
return app.not_found()
}
return app.html('username: $username | repository: $repository')
return app.html('username: ${username} | repository: ${repository}')
}
['/json_echo'; post]

View File

@@ -255,7 +255,7 @@ pub fn (mut ctx Context) file(f_path string) Result {
}
content_type := vweb.mime_types[ext]
if content_type.len == 0 {
eprintln('no MIME type found for extension $ext')
eprintln('no MIME type found for extension ${ext}')
ctx.server_error(500)
} else {
ctx.send_response_to_client(content_type, data)
@@ -273,7 +273,7 @@ pub fn (mut ctx Context) ok(s string) Result {
// Response a server error
pub fn (mut ctx Context) server_error(ecode int) Result {
$if debug {
eprintln('> ctx.server_error ecode: $ecode')
eprintln('> ctx.server_error ecode: ${ecode}')
}
if ctx.done {
return Result{}
@@ -313,10 +313,10 @@ pub fn (mut ctx Context) set_cookie(cookie http.Cookie) {
secure += if cookie.http_only { ' HttpOnly' } else { ' ' }
cookie_data << secure
if cookie.expires.unix > 0 {
cookie_data << 'expires=$cookie.expires.utc_string()'
cookie_data << 'expires=${cookie.expires.utc_string()}'
}
data := cookie_data.join(' ')
ctx.add_header('Set-Cookie', '$cookie.name=$cookie.value; $data')
ctx.add_header('Set-Cookie', '${cookie.name}=${cookie.value}; ${data}')
}
// Sets the response content type
@@ -327,7 +327,7 @@ pub fn (mut ctx Context) set_content_type(typ string) {
// TODO - test
// Sets a cookie with a `expire_data`
pub fn (mut ctx Context) set_cookie_with_expire_date(key string, val string, expire_date time.Time) {
ctx.add_header('Set-Cookie', '$key=$val; Secure; HttpOnly; expires=$expire_date.utc_string()')
ctx.add_header('Set-Cookie', '${key}=${val}; Secure; HttpOnly; expires=${expire_date.utc_string()}')
}
// Gets a cookie by a key
@@ -340,9 +340,9 @@ pub fn (ctx &Context) get_cookie(key string) !string { // TODO refactor
// println('cookie_header="$cookie_header"')
// println(ctx.req.header)
cookie := if cookie_header.contains(';') {
cookie_header.find_between(' $key=', ';')
cookie_header.find_between(' ${key}=', ';')
} else {
cookie_header.find_between(' $key=', '\r')
cookie_header.find_between(' ${key}=', '\r')
}
if cookie != '' {
return cookie.trim_space()
@@ -356,7 +356,7 @@ pub fn (mut ctx Context) set_status(code int, desc string) {
if code < 100 || code > 599 {
ctx.status = '500 Internal Server Error'
} else {
ctx.status = '$code $desc'
ctx.status = '${code} ${desc}'
}
}
@@ -393,18 +393,18 @@ pub struct RunParams {
[manualfree]
pub fn run_at<T>(global_app &T, params RunParams) ! {
if params.port <= 0 || params.port > 65535 {
return error('invalid port number `$params.port`, it should be between 1 and 65535')
return error('invalid port number `${params.port}`, it should be between 1 and 65535')
}
mut l := net.listen_tcp(params.family, '$params.host:$params.port') or {
mut l := net.listen_tcp(params.family, '${params.host}:${params.port}') or {
ecode := err.code()
return error('failed to listen $ecode $err')
return error('failed to listen ${ecode} ${err}')
}
// Parsing methods attributes
mut routes := map[string]Route{}
$for method in T.methods {
http_methods, route_path := parse_attrs(method.name, method.attrs) or {
return error('error parsing method attributes: $err')
return error('error parsing method attributes: ${err}')
}
routes[method.name] = Route{
@@ -413,7 +413,7 @@ pub fn run_at<T>(global_app &T, params RunParams) ! {
}
}
host := if params.host == '' { 'localhost' } else { params.host }
println('[Vweb] Running app on http://$host:$params.port/')
println('[Vweb] Running app on http://${host}:${params.port}/')
for {
// Create a new app object for each connection, copy global data like db connections
mut request_app := &T{}
@@ -430,7 +430,7 @@ pub fn run_at<T>(global_app &T, params RunParams) ! {
request_app.Context = global_app.Context // copy the context ref that contains static files map etc
mut conn := l.accept() or {
// failures should not panic
eprintln('accept() failed with error: $err.msg()')
eprintln('accept() failed with error: ${err.msg()}')
continue
}
spawn handle_conn<T>(mut conn, mut request_app, routes)
@@ -460,8 +460,8 @@ fn handle_conn<T>(mut conn net.TcpConn, mut app T, routes map[string]Route) {
// Request parse
req := http.parse_request(mut reader) or {
// Prevents errors from being thrown when BufferedReader is empty
if '$err' != 'none' {
eprintln('error parsing request: $err')
if '${err}' != 'none' {
eprintln('error parsing request: ${err}')
}
return
}
@@ -473,7 +473,7 @@ fn handle_conn<T>(mut conn net.TcpConn, mut app T, routes map[string]Route) {
}
// URL Parse
url := urllib.parse(req.url) or {
eprintln('error parsing path: $err')
eprintln('error parsing path: ${err}')
return
}
@@ -512,7 +512,7 @@ fn handle_conn<T>(mut conn net.TcpConn, mut app T, routes map[string]Route) {
$for method in T.methods {
$if method.return_type is Result {
route := routes[method.name] or {
eprintln('parsed attributes for the `$method.name` are not found, skipping...')
eprintln('parsed attributes for the `${method.name}` are not found, skipping...')
Route{}
}
@@ -547,7 +547,7 @@ fn handle_conn<T>(mut conn net.TcpConn, mut app T, routes map[string]Route) {
if params := route_matches(url_words, route_words) {
method_args := params.clone()
if method_args.len != method.args.len {
eprintln('warning: uneven parameters count ($method.args.len) in `$method.name`, compared to the vweb route `$method.attrs` ($method_args.len)')
eprintln('warning: uneven parameters count (${method.args.len}) in `${method.name}`, compared to the vweb route `${method.attrs}` (${method_args.len})')
}
app.$method(method_args)
return
@@ -673,7 +673,7 @@ pub fn (mut ctx Context) mount_static_folder_at(directory_path string, mount_pat
dir_path := directory_path.trim_right('/')
trim_mount_path := mount_path.trim_left('/').trim_right('/')
ctx.scan_static_directory(dir_path, '/$trim_mount_path')
ctx.scan_static_directory(dir_path, '/${trim_mount_path}')
return true
}
@@ -705,7 +705,7 @@ pub fn (ctx &Context) ip() string {
// Set s to the form error
pub fn (mut ctx Context) error(s string) {
println('vweb error: $s')
println('vweb error: ${s}')
ctx.form_error = s
}
@@ -716,7 +716,7 @@ pub fn not_found() Result {
fn send_string(mut conn net.TcpConn, s string) ! {
$if trace_response ? {
eprintln('> send_string:\n$s\n')
eprintln('> send_string:\n${s}\n')
}
conn.write(s.bytes())!
}