有哪些变化
KScript 现在每种写法只有一种。本页列出所有被重命名或移除的写法,以及应改用的写法。
这里没有任何会悄悄失败的情况,旧写法也不会继续生效。在 .kscript 文件中,旧写法会报错,并指出新写法:脚本无法运行,编辑器和 kscript check 给出的提示相同。大多数都附有修复方法:
| 命令 | 作用 |
|---|---|
kscript check --fix | 在项目的每个脚本中,尽可能重写可以自动改写的内容。 |
kscript check | 然后检查剩余的问题。 |
kscript check --fix 会改写下方标有 fix 的写法,并重命名那些只改了名字的语句和参数。即使文件因此无法运行,它也能处理。其余的是错误,错误信息会说明应当怎么写,编辑器对大多数错误都提供快速修复。
作为警告保留的是代码风格问题,而不是写法问题:return 之后的 else(KS6001)、未使用的代码(KS6002 至 KS6005)、没有类型的参数(KS6007)、同一文件中的第二种类型(KS6008)、不是 snake_case 或 PascalCase 的名称(KS6013)、缺少单位的时间长度(KS6018),以及双引号中没有任何插值内容的文本(KS6020)。XML 脚本保留 XML 自身的写法,例如 lt、属性中的逗号列表和 fields="x: int, y: int"。
文本、名称与值
| 之前 | 现在 | |
|---|---|---|
Section(title: Results) |
Section(title: "Results"):参数中的文本需要加引号,裸单词则为名称 |
修复 (KS6009) |
Button(on_click: "count += 1") |
Button(on_click: $count += 1),或 on_click: { $count += 1 }:双引号始终表示文本 |
|
'Hello $name' |
"Hello { $name }":双引号会计算花括号内的表达式。单引号则按原样保留文本 |
|
$route = "/users/{id}", "\d{3}", "a { color: red }" |
'/users/{id}'、'\d{3}'、'a { color: red }',或重复的花括号 ("/users/{{id}}"):双引号中的 { } 始终包含表达式,无论它以何开头,因此 "{ User->count() } users" 与 "{ 1 + 2 }" 会被填充 |
|
total = 3, total += 1, const tax = 0.2 |
$total = 3、$total += 1、const $tax = 0.2:变量在被赋值的地方也会有其 $ |
修复 (KS6010) |
fn($n) => $n * 2 |
fn(n) => $n * 2 |
修复 (KS6010) |
numbered: no, new_page: yes |
numbered: false、new_page: true(或单独的标志:new_page) |
修复 (KS6011) |
spawn(fn: job), tools: lookup |
spawn(fn: @job)、tools: [@lookup]:函数的命名方式为 @name |
fix (KS6012) |
files: "settings, .env" |
files: ['settings', '.env']:列表即数组 |
修复 (KS6006) |
timeout: 30, ttl: '10m' |
timeout: 30s、ttl: 10m:时间长度需带单位,且不加引号 |
修复 (KS6018) |
语句与运算符
| 之前 | 现在 | |
|---|---|---|
if $n lt 10、ge、eq、ne 在 .kscript 文件中 |
if $n < 10、>=、==、!=(XML 保留这些词;and、or 和 not 在两者中都保持原词) |
fix (KS6012) |
} else if $b { |
} elif $b { |
fix (KS6012) |
input(into = name) |
input(into: name) |
fix (KS6012) |
catch NotFound, Conflict as e |
catch NotFound | Conflict as e |
fix (KS6012) |
catch err when $err.type == 'NotFound' |
catch NotFound as err(when 仍会添加测试) |
|
match $n { case 1 { } default { } } |
match $n { 1 => { } _ => { } },与 match 表达式中的分支相同 |
|
test(name: "x", each: n, in: [1, 2], index: i) { } |
for n at i in [1, 2] { test(name: "x {$n}") { } } |
|
KScript.Window(title: "Hi") { }, KScript.input(...) |
import KScript.UI,然后是 Window(title: "Hi") { }:包只能在 import 中被引用,不会静默导入任何内容 |
类型、模型与错误
如果你的脚本将 ->type() 与 'list' 进行比较,请将该判断改为 ->is_a(list)。类型名称现在包含元素类型,例如 'number[]' 或 'any[]'。
| 之前 | 现在 | |
|---|---|---|
$Repo, as: $Repo, $User->create(...) |
Repo、as: Repo、User->create(...):类型直接以名称书写 |
修复 (KS6014) |
Repo->from($data), $Repo->new(name: 'x'), $OutOfStock->new(item: 'tea') |
Repo($data)、Repo(name: 'x')、OutOfStock(item: 'tea'):调用该名称即可生成值 |
|
类型或模型中的 age: int? |
age?: int(T? 仍用于可能为 null 的参数) |
修复 (KS6014) |
model User { unique: [email] … } |
model User(unique: [email]) { … }:选项写在方括号内 |
修复 (KS6014) |
model Post(timestamps, soft_deletes) { … } |
model Post extends [Timestamps, SoftDeletes] { … }:来自 KScript.Data 的内置混入 |
修复 (KS6014) |
catch QueryError, catch ConnectionError |
catch Query、catch Connection:没有任何类型名称以 Error 结尾 |
除以零会抛出 Math,列表位置越界会抛出 Index。两者现在都是内置类型,因此 catch Math 与 catch Index 可以使用,且编辑器能够识别。
可拥有的行与文件用户
0.35 中有两项更改会移动数据,因此从 0.33 或 0.34 升级的应用各需要一次迁移。
Ownable 同时保存用户和访客
之前,继承 Ownable 的模型将其所有者以文本形式保存在 owner 中,例如 'user:12' 或 'guest:7db08f23-…'。现在它拥有 user 和 guest 关系,分别存储在 user_id 和 guest_id 中。运行 kscript db diff:它会看到 owner 被移除、两个字段被添加,并生成一个迁移,在删除 owner 之前,于 Run 块中将每行的所有者复制过去,并附带一个 Down 块将其恢复:
<Migration>
<AddField table="notes" name="user_id" type="int" optional="yes" references="users" on_delete="cascade" />
<AddField table="notes" name="guest_id" type="uuid" optional="yes" references="guests" on_delete="cascade" />
<Run>
<for each="row" in="@db('notes')->get()">
<let name="owner" value="$row.owner ?? ''" />
<if $owner->starts_with('user:')>
<do>@db('notes')->where(id: $row.id)->update(user_id: $owner->replace('user:', '')->to_int())</do>
<continue />
</if>
<if $owner->starts_with('guest:')>
<let name="guest" value="$owner->replace('guest:', '')" />
<if @db('guests')->where(id: $guest)->count() == 0>
<do>@db('guests')->insert({ id: $guest, created_at: @now(), updated_at: @now() })</do>
</if>
<do>@db('notes')->where(id: $row.id)->update(guest_id: $guest)</do>
</if>
</for>
</Run>
<DropField table="notes" name="owner" />
</Migration>Migration {
AddField(table: 'notes', name: 'user_id', type: int, optional, references: 'users', on_delete: cascade)
AddField(table: 'notes', name: 'guest_id', type: uuid, optional, references: 'guests', on_delete: cascade)
Run {
for row in @db('notes')->get() {
$owner = $row.owner ?? ''
if $owner->starts_with('user:') {
@db('notes')->where(id: $row.id)->update(user_id: $owner->replace('user:', '')->to_int())
continue
}
if $owner->starts_with('guest:') {
$guest = $owner->replace('guest:', '')
if @db('guests')->where(id: $guest)->count() == 0 {
@db('guests')->insert({ id: $guest, created_at: @now(), updated_at: @now() })
}
@db('notes')->where(id: $row.id)->update(guest_id: $guest)
}
}
}
DropField(table: 'notes', name: 'owner')
}owner 中提到的每位访客都会在 guests 中获得一行,因此他们的行仍归属于他们。用户的 id 必须是 users 中的一行,因此请先按下文迁移文件用户。
用户迁移到 User 模型
Ownable 需要 "users": "User" 中的 http.auth,它将用户保存在 users 表中。在此之前注册的用户是应用数据文件夹中的 JSON 文件,@file_users() 会读取它们,每个文件都带有其 id、password_hash 和日期。
文件用户的 id 为 uuid,而内置的 User 使用数字键。用 kscript publish User 发布它并为其提供 uuid 键,这样会话、API 令牌和所有者仍能找到相同的人:
<import package="KScript.Data" />
<model name="User" auto_create="yes" unique="[email]" hidden="[password]" with="Timestamps">
<field name="id" type="uuid" default="@uuid()" />
<field name="name" type="string" />
<field name="email" type="email" />
<field name="password" type="password" />
</model>import KScript.Data
model User(auto_create, unique: [email], hidden: [password]) extends Timestamps {
id: uuid = @uuid()
name: string
email: email
password: password
}然后 kscript db diff 会创建 users 表,kscript make migration import_file_users 会为你生成一个将其复制过去的迁移。密码哈希按原样复制,因此每个人都可以使用原有密码登录:
<KScript.Migration>
<import package="KScript.Auth" />
<Run>
<for each="account" in="@file_users()">
<do>@db('users')->insert({
id: $account.id,
name: $account.name,
email: $account.email,
password: $account.password_hash,
created_at: $account.created_at,
updated_at: $account.updated_at,
})</do>
</for>
</Run>
<Down>
<Run>
<do>@db('users')->delete()</do>
</Run>
</Down>
</KScript.Migration>import KScript.Data
import KScript.Auth
Migration {
Run {
for account in @file_users() {
@db('users')->insert({
id: $account.id,
name: $account.name,
email: $account.email,
password: $account.password_hash,
created_at: $account.created_at,
updated_at: $account.updated_at,
})
}
}
Down {
Run {
@db('users')->delete()
}
}
}为它起一个排在 Ownable 迁移之前的名称,或将其写在前面,这样当所有者指向用户时,用户已经存在。你为用户添加的字段也要放入 insert 中,在删除之前文件保持原位。
已重命名的语句
| 之前 | 现在 |
|---|---|
before-each, after-each |
before_each, after_each |
expect-error |
expect_error |
log-provider |
log_provider |
css-text |
css_text |
marray |
collection |
已变为命令的语句
动作就是命令,因此其结果可以在表达式中使用。
| 之前 | 现在 |
|---|---|
write 语句 |
@write_text(path, text)、@append_text(path, text) 或 @write_json(path, value)(KScript.IO) |
move 和 copy 语句 |
@move(from, to)、@copy(from, to)(KScript.IO) |
delete 语句 |
@delete(path)(KScript.IO) |
mkdir 语句 |
@create_folder(path)(KScript.IO) |
assert 语句 |
@assert(condition, message?)(KScript.Test) |
stylesheet 语句 |
@stylesheet(path, vars?),返回 CSS:@write_text('site.css', @stylesheet('theme.ks.css'))(KScript.Style) |
dispatch 语句 |
作业自身的方法:SendWelcome(user_id: 7)->dispatch(),带有 delay:、at:、queue: 或 connection:(KScript.Queue) |
download 语句 |
@download(url, to),返回它所保存文件的路径(KScript.Net) |
redirect 语句 |
控制器中的 return @redirect(/thanks)(KScript.Http);页面中的 <respond redirect="/thanks" /> |
参数
参数名为 snake_case。带连字符的名称会报错,并提示新名称:max-tokens 应为 max_tokens,must-exist 应为 must_exist,new-page 应为 new_page,on-click 应为 on_click。(在页面的 HTML 标签上,on-click 保留 HTML 的连字符。)
| 语句 | 之前 | 现在 |
|---|---|---|
input, picker, menu, confirm, llm, capture, config, call |
to: name |
into: name:结果存入的变量。to 只能作为目标使用 |
for, menu |
index: i |
at: i (for item at i in $list) |
import, include, layout, Markdown, Figure, Bibliography |
src |
path |
type |
sample |
path |
Table(KScript.Document) |
data, headers, align: "lrr" |
rows、columns: { Name: 'name' }、align: ['left', 'right'],如同终端中的 table |
wait |
ms, seconds |
duration: 500ms,或单独的值:wait(500ms) |
test |
each, in, index |
围绕该测试的 for 循环(见上文) |
@color, log_provider |
colour |
color |
命令
| 之前 | 现在 |
|---|---|
@to_upper($t), @to_lower($t) |
$t->upper(), $t->lower() |
@string($v), @number($t), @date($t), @type($v) |
$v->to_string(), $t->to_number(), $t->to_date(), $v->type() |
@json($t), @to_json($v), @yaml($t), @to_yaml($v) |
$t->convert(from: json), $v->convert(to: json), $t->convert(from: yaml), $v->convert(to: yaml) |
@escape($t), @base64($t), @url_encode($t), @url_decode($t) |
$t->escape(), $t->to_base64(), $t->url_encode(), $t->url_decode() |
@pow($a, $b) |
$a ** $b |
@guid() |
@uuid() |
@contrast(...) |
@contrast_color(color, dark?, light?) |
@signed_in() |
@is_signed_in() |
@log(8, 2) |
@logarithm(8, 2)(log 是写入日志条目的语句) |
@config('database.port', 5432) |
$config.database.port,或 $config->get('database.port', 5432) |
@exit(1), @error('Too short') |
exit 1, throw Validation "Too short" |
@transaction(...) |
transaction 语句,或 $db->transaction(fn) |
方法与字段
关于某个值的简单事实是字段,使用点号读取,不带方括号:$file.name、$file.size、$response.status、$date.year。调用字段($file->name())会报错并说明原因。对任何值都可用 ->count() 进行计数。
| 在 | 之前 | 现在 |
|---|---|---|
| 列表、映射、文本 | ->length() |
->count() |
| 文本 | $text->is_empty() 用于接受空文本或仅含空白的文本 |
请为该检查使用 $text->is_blank()。$text->is_empty() 现在检测零个字符。 |
| 列表 | ->where(fn), ->append(item) |
->filter(fn), ->push(item) |
| 列表 | $items->count_of($value) 用于统计严格匹配的数量 |
严格匹配请使用 $items->count_of(fn(x) => $x === $value)。传入值现在与 == 比较。 |
| 数字 | ->pow(2) |
$n ** 2 |
| 数字 | $n->between(1, 10) |
1 <= $n <= 10,一条比较链 |
| 响应 | ->ok() |
.is_ok |
| IP | ->private(), ->loopback() |
.is_private, .is_loopback |
| JWT | ->expired() |
.is_expired |
| 数据库 | ->in_transaction() |
.is_in_transaction |
| 密码 | ->strong() |
->is_strong() |
| 日志记录器 | ->enabled(level) |
->is_enabled(level) |
| 时区 | ->dst() |
->is_dst() |
| 缓存 | ->put(key, value), ->forget(key), ->flush() |
->set(key, value), ->remove(key), ->clear() |
| 会话 | ->put(key, value), ->forget(key) |
->set(key, value), ->remove(key) |
| 存储文件夹 | ->path(name) |
->path_of(name);.path 即文件夹本身 |
| 颜色 | ->contrast(other) |
->contrast_ratio(other) |
| 查询、模型 | ->avg(column) |
->average(column) |
| URL | ->with_query(values) |
->with(query: values);->without(query, fragment) 会去掉整段部分 |
| 日期 | ->add_years(n), ->add_months(n), ->add_days(n) |
->add(years: n, months: n, days: n),也可用 weeks:;->subtract(...) 则回退 |
| 日期 | ->add_hours(n), ->add_minutes(n) |
时长:$date + 3h、$date - 45m |
| 日期 | ->duration_since(other) |
$date - $other,即一个时长 |
| 日期 | ->months_since(other), ->years_since(other) |
->since(other, in: months)、->since(other, in: years)(也可用 days 和 weeks) |
| 日期 | $date + 1、$date - 1(天)、$a - $b(天数) |
$date + 1d 或 ->add(days: 1);$a - $b 现在是一个时长 |
| 时长 | ->plus(other), ->minus(other) |
->add(other), ->subtract(other) |
| 文本 | ->trim_start(chars?), ->trim_end(chars?) |
->trim(start), ->trim(chars, end) |
| 文本 | ->pad_left(width, char?), ->pad_right(width, char?) |
->pad(width, char?, start), ->pad(width, char?) |
| 文本 | ->strip_prefix(text), ->strip_suffix(text) |
->strip(prefix: text)、->strip(suffix: text),或同时使用两者 |
| 文本 | ->before_last(text), ->after_last(text), ->last_index_of(text) |
->before(text, last), ->after(text, last), ->index_of(text, last) |
| 文本 | ->replace_pattern(pattern, replacement) |
->replace(/pattern/, replacement),分组时可用 $1 或 ${name} |
| 文本 | ->snake_case(), ->kebab_case(), ->camel_case(), ->pascal_case() |
->case(snake), ->case(kebab), ->case(camel), ->case(pascal) |
| 列表 | ->find_last(fn), ->find_index(fn) |
->find(fn, last)、->index_of(fn)(也可用 last) |
| 列表、映射 | ->sort_by(fn, desc) |
->sort(by: fn, order: desc) |
| 列表 | ->max_by(fn), ->min_by(fn), ->unique_by(fn) |
->max(by: fn), ->min(by: fn), ->unique(by: fn) |
| 列表 | ->reduce(fn) 无初始值,从 null 开始 |
与 ->scan() 一样,第一项即为第一个总计值:[3, 5, 2]->reduce(fn(total, n) => $total + $n) 为 10 |
| 映射 | ->reduce(fn) 无初始值,从 null 开始 |
与列表一样,第一个值即为第一个总计值:{ apples: 3, pears: 5 }->reduce(fn(total, n) => $total + $n) 为 8 |
| 列表 | ->most_common(count?) |
->common(count?),或用 ->common(count?, least) 取最稀有的第一项 |
| 数字 | -5->abs() 解读为 -(5->abs()),即 -5 |
直接写在数字上的负号属于该数字,因此 -5->abs() 为 5;-$x->abs() 仍会对 ->abs() 的结果取反 |
| JSON | ->parse() |
->convert(from: json) |
| 文本、响应 | ->json(as?), ->yaml(), ->csv(header?, as?), ->markdown() |
->convert(from: json, as?)、->convert(from: yaml)、->convert(from: csv, not header, as?)、->convert(from: markdown, to: html);->from(type: json) 为简写形式 |
| 任意值 | ->to_json(indented?)、->to_yaml()、列表的 ->to_csv(headers?) |
->convert(to: json, indented)、->convert(to: yaml)、->convert(to: csv, headers: [...]);->to(type: json) 为简写形式 |
| 文档、Markdown、LaTeX | ->html(), ->latex(), ->markdown() |
->convert(to: html), ->convert(to: latex), ->convert(to: markdown) |
| CSV | ->rows(header?, as?), ->column(at, header?, as?) |
->cells(header?, as?)、->cells(column: at, header?, as?);->cells(row: 0) 读取一行,->cells(columns) 读取每一列,->cells(row: 0, column: 'price') 读取一个单元格。以数字书写的单元格即为数字,表头由第一行推断得出 |
用于 ->shapes(like:) 的遮罩 |
任意带有 layout: string = ... 和 symbols: map = ... 的类型 |
type Tree extends Mask { layout: ..., symbols: { ... } }:只有扩展了 Mask 的类型才是遮罩,其成员无需声明类型 |
| 遮罩 | $grid->shapes(like: Tree, rotated) |
$input->shapes(Tree, rotated):遮罩须放在最前,文本、列表或三维列表与网格一样可用,因此 ->grid() 不必排在最前。like: 是一个错误,附带可改写该调用的修复方案 |
| 遮罩 | symbols: { '#': '#', '.': null },列出每个字符 |
symbols: { '.': any }:字符默认与自身匹配,除非 symbols 另有指定,因此无需更改的遮罩不需要 symbols。null 是一个错误,修复方案会写入 any;'#': '#' 是一个警告(KS6025),修复方案会将其删除 |
| 遮罩 | layout = ..., symbols = ... |
layout: ...、symbols: ...:遮罩的成员使用冒号书写,编辑器的修复会改写为 =。遮罩只能包含 layout、symbols 和方法 |
| 多列表的列表 | ->transpose() |
->cells(columns),用于像读取 csv 那样读取 ->grid() 或任何多列表的列表:->cells(rows)、->cells(row: 0)、->cells(column: 2) 和 ->cells(row: 0, column: 2)。允许行的长度不同:列会跳过长度不足以到达该列的行 |
命令行
| 命令 | 之前 | 现在 |
|---|---|---|
kscript check, kscript queue |
--format text|json |
--output text|json |
kscript check |
--warnaserror |
--warnings-as-errors |
kscript openapi |
--yaml, --json |
--output yaml, --output json |
kscript make, kscript docs, kscript mcp |
--format kscript|xml |
--syntax kscript|xml |
kscript convert |
--to kscript|xml |
--syntax kscript|xml |
kscript make |
kscript make:component Hero |
kscript make component Hero |
kscript update |
--version v0.34.0、--tag v0.34.0(用该版本替换已安装的 kscript) |
kscript version use 0.34.0,两种写法并排保留,以便切换回去(见切换版本) |
kscript version |
输出版本号 | kscript --version 输出版本号;kscript version 显示当前运行的版本及其选择方式 |
| 任意命令 | --debug(显示错误背后的 .NET 堆栈跟踪) |
--stack-trace |
| 任意命令 | KSCRIPT_DEBUG=1 |
KSCRIPT_STACK_TRACE=1 |
--output 始终指定结果的输出方式,--syntax 始终指定脚本所用的两种写法之一。
--debug 现在会在终端调试器中运行脚本。使用其他命令时,它会报错并指出 --stack-trace。
kscript check --output json 写入的键采用 snake_case:end_line、end_column 与 new_text(原为 endLine、endColumn 与 newText),与 KScript 自身 JSON 中的其他键保持一致。各命令的退出码相同:检查或测试失败时为 1,命令行或设置有误时为 2,脚本因错误而停止时为 3。
kscript.json
键为 snake_case。旧键会报错,并提示新键名。
| 之前 | 现在 |
|---|---|
lint.warningsAsErrors |
lint.warnings_as_errors |
format.tabWidth, format.printWidth |
format.tab_width, format.print_width |
format.maxBlankLines, format.endOfLine |
format.max_blank_lines, format.end_of_line |
format.rules.statementPerLine, tidyTags, wrapAttributes |
format.rules.statement_per_line, tidy_tags, wrap_attributes |
format.rules.trimTrailingWhitespace, collapseBlankLines, finalNewline |
format.rules.trim_trailing_whitespace, collapse_blank_lines, final_newline |
format.rules.braceStyle, wrapStrings, wrapChains, wrapBodies, wrapComments |
format.rules.brace_style, wrap_strings, wrap_chains, wrap_bodies, wrap_comments |
make.format |
make.syntax |
config 部分现在只保存应用自身的设置,其中不再指定要加载的文件。config.files 会报错,并说明其中每个文件应放在哪里:
| 之前 | 现在 |
|---|---|
"config": { "files": ["config/config.kscript"] } |
config.kscript 位于 kscript.json 旁边,单独读取。其 configure(environment) 仍像以前一样被调用 |
".env",位于 config.files 中的 ".env?" |
无:.env 和 .env.<env> 单独读取,用于 @env() |
config/config.yaml |
kscript.json 中 "config" 部分的值,以及某一环境专用的 kscript.<env>.json |
config.root, config.prefix, config.required, config.user, paths.config |
已移除。app.user_config 将设置保存在用户自己的文件夹中 |
$config->sources() 列出已读取的文件,便于你确认配置已加载。
名称
你自己的名称遵循与内置名称相同的规则,违反规则的名称会产生警告(KS6013):函数、变量、字段和参数为 snake_case,类型、模型、枚举和错误类型为 PascalCase。将 fn sendEmail() 重命名为 fn send_email(),将 type repo 重命名为 type Repo。
内置名称不会再偏离这些规则。引擎会在包注册每个语句、参数、命令、方法和字段时进行检查,并拒绝违反规则的名称,因此新包无法重新引入带连字符的参数,或为 ->count() 引入第二个名称。KScript 开发中列出了这些规则。
文件
| 之前 | 现在 |
|---|---|
以 <kscript> 开头的 hello.ks,或普通的 hello.xml |
hello.ks.xml 用于 XML 形式,hello.kscript 用于默认形式 |
name.test.xml |
name.test.ks.xml 或 name.test.kscript |
由 kscript make 写入、在 snake_case 中指定的文件 |
kebab-case 文件名:middleware/request-id.kscript、lib/notes-client.kscript |
kscript convert 可以把脚本在两种形式之间转换,并重命名指向它的导入。见.kscript 格式。