all: super_batch3 fixes

This commit is contained in:
Alexander Medvednikov committed 2026-04-13 04:18:00 +03:00
1 parent 56a477ed8c
commit e2e5cf8db5
634 files changed
+6379 -4284

No files matched your search

+1
View File
@@ -173,3 +173,4 @@ issue*
# ignore cmd2/v stuff
cmd/v2/*.txt
cmd/v2/*.json
.claude/
+10 -3
View File
@@ -1,4 +1,5 @@
import common { Task, exec }
import os
fn test_symlink() {
exec('v symlink')
@@ -17,7 +18,8 @@ fn all_code_is_formatted() {
if common.is_github_job {
exec('VJOBS=1 v -silent test-cleancode')
} else {
exec('v -progress test-cleancode')
vjobs := os.getenv_opt('VJOBS') or { '1' }
exec('VJOBS=${vjobs} v -progress test-cleancode')
}
}
@@ -38,7 +40,11 @@ fn verify_v_test_works() {
}
fn install_iconv() {
exec('brew install libiconv')
// Skip Homebrew when iconv is already linkable for V on this machine.
if os.system('v -silent test vlib/encoding/iconv/') == 0 {
return
}
exec('brew list --versions libiconv >/dev/null 2>&1 || brew install libiconv')
}
fn test_pure_v_math_module() {
@@ -49,7 +55,8 @@ fn self_tests() {
if common.is_github_job {
exec('VJOBS=1 v -silent test-self vlib')
} else {
exec('v -progress test-self vlib')
vjobs := os.getenv_opt('VJOBS') or { '1' }
exec('VJOBS=${vjobs} v -progress test-self vlib')
}
}
+1 -2
View File
@@ -30,8 +30,7 @@ fn main() {
checksum = 0
for len in str_lens {
end_pos := start_pos + len
checksum ^= wyhash.wyhash_c(unsafe { &u8(bytepile.data) + start_pos }, u64(len),
1)
checksum ^= wyhash.wyhash_c(unsafe { &u8(bytepile.data) + start_pos }, u64(len), 1)
start_pos = end_pos
}
bhashing_1.measure('wyhash.wyhash_c | checksum: ${checksum:22}')
+1 -2
View File
@@ -55,8 +55,7 @@ fn main() {
}
}
if diff_modules.len > 0 {
eprintln(term.header('Found ${diff_modules.len} modules with different APIs',
'='))
eprintln(term.header('Found ${diff_modules.len} modules with different APIs', '='))
for m in diff_modules.keys() {
eprintln('Module: ${m}')
}
+2 -1
View File
@@ -62,7 +62,8 @@ fn main() {
elog('fast_job clone output repos...')
check_output_repo('https://github.com/vlang/website', 'gh-pages', 'fast.vlang.io/')
check_output_repo('https://github.com/vlang/docs/', 'main', 'docs.vlang.io/')
check_output_repo('https://github.com/vlang/docs/', 'generator', 'docs.vlang.io/docs_generator/')
check_output_repo('https://github.com/vlang/docs/', 'generator',
'docs.vlang.io/docs_generator/')
mut i := 0
for {
+5 -4
View File
@@ -230,8 +230,10 @@ fn (mut gen_vc GenVC) generate() {
gen_vc.cmd_exec('git clone --filter=blob:none https://${git_repo_v} ${git_repo_dir_v}')
gen_vc.cmd_exec('git clone --filter=blob:none https://${git_repo_vc} ${git_repo_dir_vc}')
// get output of git log -1 (last commit)
git_log_v := gen_vc.cmd_exec('git -C ${git_repo_dir_v} log -1 --format="commit %H%nDate: %ci%nDate Unix: %ct%nSubject: %s"')
git_log_vc := gen_vc.cmd_exec('git -C ${git_repo_dir_vc} log -1 --format="Commit %H%nDate: %ci%nDate Unix: %ct%nSubject: %s"')
git_log_v :=
gen_vc.cmd_exec('git -C ${git_repo_dir_v} log -1 --format="commit %H%nDate: %ci%nDate Unix: %ct%nSubject: %s"')
git_log_vc :=
gen_vc.cmd_exec('git -C ${git_repo_dir_vc} log -1 --format="Commit %H%nDate: %ci%nDate Unix: %ct%nSubject: %s"')
// date of last commit in each repo
ts_v := git_log_v.find_between('Date:', '\n').trim_space()
ts_vc := git_log_vc.find_between('Date:', '\n').trim_space()
@@ -246,8 +248,7 @@ fn (mut gen_vc GenVC) generate() {
last_commit_hash_v := git_log_v.find_between('commit', '\n').trim_space()
last_commit_hash_v_short := last_commit_hash_v[..7]
// subject
last_commit_subject := git_log_v.find_between('Subject:', '\n').trim_space().replace("'",
'"')
last_commit_subject := git_log_v.find_between('Subject:', '\n').trim_space().replace("'", '"')
// log some info
gen_vc.logger.debug('last commit time (${git_repo_v}): ' + last_commit_time_v.format_ss())
gen_vc.logger.debug('last commit time (${git_repo_vc}): ' + last_commit_time_vc.format_ss())
+2 -1
View File
@@ -28,7 +28,8 @@ fn main() {
mut n := 0
for start := 0; start < original.len; {
gc_collect()
idx := original.index_after_(separator, start + separator.len) // ensure that we advance each time
idx :=
original.index_after_(separator, start + separator.len) // ensure that we advance each time
if idx < 0 {
write_chunk(n, min_size, original, start, original.len)
break
+2 -1
View File
@@ -29,7 +29,8 @@ import term
fn main() {
// This hook cares only about the changed V files, that will be committed, as reported by git itself:
changed := os.execute('git diff --cached --name-only --diff-filter=ACMR -- "*.v" "*.vsh" "*.vv"')
changed :=
os.execute('git diff --cached --name-only --diff-filter=ACMR -- "*.v" "*.vsh" "*.vv"')
all_changed_vfiles := changed.output.trim_space().split('\n')
// _input.vv files are NOT formatted on purpose.
+2 -1
View File
@@ -83,7 +83,8 @@ fn process_files(files []string) ! {
theader()
hline()
speed_mb_s := term.colorize(term.bright_yellow, '${(f64(total_bytes) / total_us):6.3f} MB/s')
speed_lines_s := term.colorize(term.bright_yellow, '${(1_000_000 * f64(total_lines) / total_us):10.1f} lines/s')
speed_lines_s := term.colorize(term.bright_yellow,
'${(1_000_000 * f64(total_lines) / total_us):10.1f} lines/s')
println('${total_us:10}us ${total_tokens:10} ${total_bytes:10} ${total_lines:10} ${(f64(total_bytes) / total_tokens):13.3} ${total_errors:10} ${total_fmt_len:7} FMT speed: ${speed_mb_s}, ${speed_lines_s}, ${nthreads:3} thread(s), ${total_files:5} files.')
}
+2 -1
View File
@@ -81,7 +81,8 @@ fn process_files(files []string) ! {
theader()
hline()
speed_mb_s := term.colorize(term.bright_yellow, '${(f64(total_bytes) / total_us):6.3f} MB/s')
speed_lines_s := term.colorize(term.bright_yellow, '${(1_000_000 * f64(total_lines) / total_us):10.1f} lines/s')
speed_lines_s := term.colorize(term.bright_yellow,
'${(1_000_000 * f64(total_lines) / total_us):10.1f} lines/s')
println('${total_us:10}us ${total_tokens:10} ${total_bytes:10} ${total_lines:10} ${(f64(total_bytes) / total_tokens):13.3} ${total_errors:10} Parser speed: ${speed_mb_s}, ${speed_lines_s}, ${nthreads:3} thread(s), ${total_files:5} files.')
}
+2 -1
View File
@@ -70,6 +70,7 @@ fn process_files(files []string) ! {
theader()
hline()
speed_mb_s := term.colorize(term.bright_yellow, '${(f64(total_bytes) / total_us):6.3f} MB/s')
speed_lines_s := term.colorize(term.bright_yellow, '${(1_000_000 * f64(total_lines) / total_us):10.1f} lines/s')
speed_lines_s := term.colorize(term.bright_yellow,
'${(1_000_000 * f64(total_lines) / total_us):10.1f} lines/s')
println('${total_us:10}us ${total_tokens:10} ${total_bytes:10} ${total_lines:10} ${(f64(total_bytes) / total_tokens):13.3} ${total_errors:10} Scanner speed: ${speed_mb_s}, ${speed_lines_s}, ${nthreads:3} thread(s), ${total_files:5} files.')
}
+14 -10
View File
@@ -331,7 +331,8 @@ fn (mut ts TestSession) handle_test_runner_option() {
if test_runner !in pref.supported_test_runners {
eprintln('v test: `-test-runner ${test_runner}` is not using one of the supported test runners: ${pref.supported_test_runners_list()}')
}
test_runner_implementation_file := os.join_path(ts.vroot, 'cmd/tools/modules/testing/output_${test_runner}.v')
test_runner_implementation_file := os.join_path(ts.vroot,
'cmd/tools/modules/testing/output_${test_runner}.v')
if !os.exists(test_runner_implementation_file) {
eprintln('v test: using `-test-runner ${test_runner}` needs ${test_runner_implementation_file} to exist, and contain a valid testing.Reporter implementation for that runner. See `cmd/tools/modules/testing/output_dump.v` for an example.')
exit(1)
@@ -452,7 +453,8 @@ fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr {
tls_bench.njobs = ts.benchmark.njobs
abs_path := os.real_path(p.get_item[string](idx))
mut relative_file := abs_path
mut cmd_options := vflags.tokenize_to_args(ts.vargs) // make sure that `'-W -silent'` becomes `['-W', '-silent']`, while keeping quoted spaces intact
mut cmd_options :=
vflags.tokenize_to_args(ts.vargs) // make sure that `'-W -silent'` becomes `['-W', '-silent']`, while keeping quoted spaces intact
mut run_js := false
is_fmt := ts.vargs.contains('fmt')
@@ -590,7 +592,8 @@ fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr {
os.setenv('VTEST_RETRY_MAX', '${details.retry}', true)
for retry := 1; retry <= details.retry; retry++ {
if !details.hide_retries {
ts.append_message(.info, ' [stats] retrying ${retry}/${details.retry} of ${relative_file} ; known flaky: ${details.flaky} ...',
ts.append_message(.info,
' [stats] retrying ${retry}/${details.retry} of ${relative_file} ; known flaky: ${details.flaky} ...',
mtc)
}
os.setenv('VTEST_RETRY', '${retry}', true)
@@ -613,7 +616,8 @@ fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr {
time.sleep(fail_retry_delay_ms)
}
if details.flaky && !fail_flaky {
ts.append_message(.info, ' *FAILURE* of the known flaky test file ${relative_file} is ignored, since VTEST_FAIL_FLAKY is 0 . Retry count: ${details.retry} .\ncmd: ${cmd}',
ts.append_message(.info,
' *FAILURE* of the known flaky test file ${relative_file} is ignored, since VTEST_FAIL_FLAKY is 0 . Retry count: ${details.retry} .\ncmd: ${cmd}',
mtc)
unsafe {
goto test_passed_system
@@ -630,8 +634,7 @@ fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr {
}
} else {
if show_start {
ts.append_message(.info, ' starting ${relative_file} ...',
mtc)
ts.append_message(.info, ' starting ${relative_file} ...', mtc)
}
ts.append_message(.compile_begin, cmd, mtc)
compile_d_cmd := time.new_stopwatch()
@@ -645,8 +648,7 @@ fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr {
}
random_sleep_ms(50, 100 * cretry)
}
ts.append_message_with_duration(.compile_end, compile_r.output, compile_cmd_duration,
mtc)
ts.append_message_with_duration(.compile_end, compile_r.output, compile_cmd_duration, mtc)
if compile_r.exit_code != 0 {
ts.benchmark.fail()
tls_bench.fail()
@@ -690,7 +692,8 @@ fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr {
os.setenv('VTEST_RETRY_MAX', '${details.retry}', true)
for retry = 1; retry <= details.retry; retry++ {
if !details.hide_retries {
ts.append_message(.info, ' retrying ${retry}/${details.retry} of ${relative_file} ; known flaky: ${details.flaky} ...',
ts.append_message(.info,
' retrying ${retry}/${details.retry} of ${relative_file} ; known flaky: ${details.flaky} ...',
mtc)
}
os.setenv('VTEST_RETRY', '${retry}', true)
@@ -717,7 +720,8 @@ fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr {
for line in full_failure_output.split_into_lines() {
ts.append_message(.info, '>>>>>> ${line}', mtc)
}
ts.append_message(.info, ' *FAILURE* of the known flaky test file ${relative_file} is ignored, since VTEST_FAIL_FLAKY is 0 . Retry count: ${details.retry} .\n comp_cmd: ${cmd}\n run_cmd: ${run_cmd}',
ts.append_message(.info,
' *FAILURE* of the known flaky test file ${relative_file} is ignored, since VTEST_FAIL_FLAKY is 0 . Retry count: ${details.retry} .\n comp_cmd: ${cmd}\n run_cmd: ${run_cmd}',
mtc)
unsafe {
goto test_passed_execute
+18 -9
View File
@@ -80,12 +80,14 @@ pub fn prepare_vc_source(vcdir string, cdir string, commit string) (string, stri
// we need the following, otherwise --grep= below would find a93ef6e, which does include 5b7a1e8 in the commit message ... 🤦‍♂️
partial_hash = '5b7a1e84a4d283071d12cb86dc17aeda9b5306a8'
}
vcbefore_subject_match := scripting.run('git rev-list HEAD -n1 --timestamp --grep=${partial_hash} ')
vcbefore_subject_match :=
scripting.run('git rev-list HEAD -n1 --timestamp --grep=${partial_hash} ')
scripting.verbose_trace(@FN, 'vcbefore_subject_match: ${vcbefore_subject_match}')
if vcbefore_subject_match.len > 3 {
_, vccommit = line_to_timestamp_and_commit(vcbefore_subject_match)
} else {
scripting.verbose_trace(@FN, 'the v commit did not match anything in the vc log; try --timestamp instead.')
scripting.verbose_trace(@FN,
'the v commit did not match anything in the vc log; try --timestamp instead.')
vcbefore := scripting.run('git rev-list HEAD -n1 --timestamp --before=${v_timestamp} ')
_, vccommit = line_to_timestamp_and_commit(vcbefore)
}
@@ -170,7 +172,8 @@ pub mut:
pub fn (mut vgit_context VGitContext) compile_oldv_if_needed() {
vgit_context.vexename = if os.user_os() == 'windows' { 'v.exe' } else { 'v' }
vgit_context.vexepath = os.real_path(os.join_path_single(vgit_context.path_v, vgit_context.vexename))
vgit_context.vexepath = os.real_path(os.join_path_single(vgit_context.path_v,
vgit_context.vexename))
if os.is_dir(vgit_context.path_v) && os.is_executable(vgit_context.vexepath)
&& !vgit_context.show_vccommit {
// already compiled, no need to compile that specific v executable again
@@ -253,11 +256,15 @@ pub fn (mut vgit_context VGitContext) compile_oldv_if_needed() {
if vgit_context.commit_v__ts >= 1699341818 && !vgit_context.cc.contains('msvc') {
c_flags += '-lws2_32'
}
command_for_building_v_from_c_source = c(vgit_context.cc, '${vc_v_cpermissive_flags} ${c_flags} -o cv.exe "${vc_source_file_location}" ${c_ldflags}')
command_for_selfbuilding = c('.\\cv.exe', '${vc_v_bootstrap_flags} -cflags "${vc_v_cpermissive_flags}" -o ${vgit_context.vexename} {SOURCE}')
command_for_building_v_from_c_source = c(vgit_context.cc,
'${vc_v_cpermissive_flags} ${c_flags} -o cv.exe "${vc_source_file_location}" ${c_ldflags}')
command_for_selfbuilding = c('.\\cv.exe',
'${vc_v_bootstrap_flags} -cflags "${vc_v_cpermissive_flags}" -o ${vgit_context.vexename} {SOURCE}')
} else {
command_for_building_v_from_c_source = c(vgit_context.cc, '${vc_v_cpermissive_flags} ${c_flags} -o cv "${vc_source_file_location}" ${c_ldflags}')
command_for_selfbuilding = c('./cv', '${vc_v_bootstrap_flags} -cflags "${vc_v_cpermissive_flags}" -o ${vgit_context.vexename} {SOURCE}')
command_for_building_v_from_c_source = c(vgit_context.cc,
'${vc_v_cpermissive_flags} ${c_flags} -o cv "${vc_source_file_location}" ${c_ldflags}')
command_for_selfbuilding = c('./cv',
'${vc_v_bootstrap_flags} -cflags "${vc_v_cpermissive_flags}" -o ${vgit_context.vexename} {SOURCE}')
}
scripting.run(command_for_building_v_from_c_source)
@@ -282,8 +289,10 @@ pub mut:
}
pub fn add_common_tool_options(mut context VGitOptions, mut fp flag.FlagParser) []string {
context.workdir = os.real_path(fp.string('workdir', `w`, context.workdir, 'A writable base folder. Default: ${context.workdir}'))
context.v_repo_url = fp.string('vrepo', 0, context.v_repo_url, 'The url of the V repository. You can clone it locally too. See also --vcrepo below.')
context.workdir = os.real_path(fp.string('workdir', `w`, context.workdir,
'A writable base folder. Default: ${context.workdir}'))
context.v_repo_url = fp.string('vrepo', 0, context.v_repo_url,
'The url of the V repository. You can clone it locally too. See also --vcrepo below.')
context.vc_repo_url = fp.string('vcrepo', 0, context.vc_repo_url, 'The url of the vc repository. You can clone it
${flag.space}beforehand, and then just give the local folder
${flag.space}path here. That will eliminate the network ops
+2 -1
View File
@@ -17,7 +17,8 @@ fn copy_to_clipboard_with_commands(text string, commands []ClipboardCommand) boo
if text.len == 0 || commands.len == 0 {
return false
}
temp_file := os.join_path(os.vtmp_dir(), 'vshare_clipboard_${os.getpid()}_${time.now().unix_micro()}.txt')
temp_file := os.join_path(os.vtmp_dir(),
'vshare_clipboard_${os.getpid()}_${time.now().unix_micro()}.txt')
os.write_file(temp_file, text) or { return false }
defer {
os.rm(temp_file) or {}
+15 -23
View File
@@ -83,23 +83,9 @@ fn sync_cache() {
scripting.chdir(cache_oldv_folder)
for reponame in ['v', 'vc'] {
repofolder := os.join_path(cache_oldv_folder, reponame)
if !os.exists(repofolder) {
scripting.verbose_trace(@FN, 'cloning to ${repofolder}')
mut repo_options := ''
if reponame == 'vc' {
repo_options = '--filter=blob:none'
}
scripting.exec('git clone ${repo_options} --quiet https://github.com/vlang/${reponame} ${repofolder}') or {
scripting.verbose_trace(@FN, '## error during clone: ${err}')
exit(1)
}
}
scripting.chdir(repofolder)
scripting.exec('git pull --quiet') or {
scripting.verbose_trace(@FN, 'pulling to ${repofolder}')
scripting.verbose_trace(@FN, '## error during pull: ${err}')
exit(1)
}
repo_url := 'https://github.com/vlang/${reponame}'
scripting.verbose_trace(@FN, 'syncing ${repo_url} to ${repofolder}')
vgit.clone_or_pull(repo_url, repofolder)
}
scripting.verbose_trace(@FN, 'done')
}
@@ -124,7 +110,8 @@ fn main() {
fp.description(tool_description)
fp.arguments_description('VCOMMIT')
fp.skip_executable()
context.use_cache = fp.bool('cache', `u`, true, 'Use a cache of local repositories for --vrepo and --vcrepo in \$HOME/.cache/oldv/')
context.use_cache = fp.bool('cache', `u`, true,
'Use a cache of local repositories for --vrepo and --vcrepo in \$HOME/.cache/oldv/')
if context.use_cache {
context.vgo.v_repo_url = cache_oldv_folder_v
context.vgo.vc_repo_url = cache_oldv_folder_vc
@@ -132,17 +119,22 @@ fn main() {
context.vgo.v_repo_url = 'https://github.com/vlang/v'
context.vgo.vc_repo_url = 'https://github.com/vlang/vc'
}
context.cc = fp.string('cc', 0, 'cc', 'Use this C compiler for bootstrapping v.c (defaults to `cc`).')
context.cc_options = fp.string('ccoptions', 0, '', 'Use these C compiler options for bootstrapping v.c (defaults to ``).')
context.cc = fp.string('cc', 0, 'cc',
'Use this C compiler for bootstrapping v.c (defaults to `cc`).')
context.cc_options = fp.string('ccoptions', 0, '',
'Use these C compiler options for bootstrapping v.c (defaults to ``).')
env_cc_options := os.getenv('OLDV_CCOPTIONS')
if env_cc_options != '' {
context.cc_options = env_cc_options
}
context.cleanup = fp.bool('clean', 0, false, 'Clean before running (slower).')
context.fresh_tcc = fp.bool('fresh_tcc', 0, true, 'Do `make fresh_tcc` when preparing a V compiler.')
context.fresh_tcc = fp.bool('fresh_tcc', 0, true,
'Do `make fresh_tcc` when preparing a V compiler.')
context.cmd_to_run = fp.string('command', `c`, '', 'Command to run in the old V repo.\n')
context.show_vccommit = fp.bool('show_VC_commit', 0, false, 'Show the VC commit, that can be used to compile the given V commit, and exit.\n')
context.is_bisect = fp.bool('bisect', `b`, false, 'Bisect mode. Use the current commit in the repo where oldv is.')
context.show_vccommit = fp.bool('show_VC_commit', 0, false,
'Show the VC commit, that can be used to compile the given V commit, and exit.\n')
context.is_bisect = fp.bool('bisect', `b`, false,
'Bisect mode. Use the current commit in the repo where oldv is.')
should_sync := fp.bool('cache-sync', `s`, false, 'Update the local cache')
if !should_sync && !context.is_bisect {
+8 -4
View File
@@ -144,8 +144,10 @@ fn (c Context) compare_v_performance(label string, commands []string) string {
} else {
source_location_b = if os.exists('${c.b}/v.v') { 'v.v ' } else { 'compiler/ ' }
}
timestamp_a, _ := vgit.line_to_timestamp_and_commit(scripting.run('cd ${c.a}/ ; git rev-list -n1 --timestamp HEAD'))
timestamp_b, _ := vgit.line_to_timestamp_and_commit(scripting.run('cd ${c.b}/ ; git rev-list -n1 --timestamp HEAD'))
timestamp_a, _ :=
vgit.line_to_timestamp_and_commit(scripting.run('cd ${c.a}/ ; git rev-list -n1 --timestamp HEAD'))
timestamp_b, _ :=
vgit.line_to_timestamp_and_commit(scripting.run('cd ${c.b}/ ; git rev-list -n1 --timestamp HEAD'))
// 1570877641 is 065ce39 2019-10-12
debug_option_a := if timestamp_a > 1570877641 { '-cg ' } else { '-debug ' }
debug_option_b := if timestamp_b > 1570877641 { '-cg ' } else { '-debug ' }
@@ -170,7 +172,8 @@ fn (c Context) compare_v_performance(label string, commands []string) string {
])
}
// /////////////////////////////////////////////////////////////////////////////
cmd_stats_file := os.real_path([c.vgo.workdir, 'v_performance_stats_${label}.json'].join(os.path_separator))
cmd_stats_file :=
os.real_path([c.vgo.workdir, 'v_performance_stats_${label}.json'].join(os.path_separator))
comparison_cmd := 'hyperfine ${c.hyperfineopts} ' + '--export-json ${cmd_stats_file} ' +
'--time-unit millisecond ' + '--style full --warmup ${c.warmups} ' +
hyperfine_commands_arguments.join(' ')
@@ -197,7 +200,8 @@ fn main() {
fp.arguments_description('COMMIT_BEFORE [COMMIT_AFTER]')
fp.skip_executable()
fp.limit_free_args(1, 2)!
context.vflags = fp.string('vflags', 0, '', 'Additional options to pass to the v commands, for example "-cc tcc"')
context.vflags = fp.string('vflags', 0, '',
'Additional options to pass to the v commands, for example "-cc tcc"')
context.hyperfineopts = fp.string('hyperfine_options', 0, '', 'Additional options passed to hyperfine.
${flag.space}For example on linux, you may want to pass:
${flag.space}--hyperfine_options "--prepare \'sync; echo 3 | sudo tee /proc/sys/vm/drop_caches\'"
+4 -2
View File
@@ -43,8 +43,10 @@ fn main() {
fp.skip_executable()
context.new_commit = fp.string('new', `n`, 'master', 'The new commit, by default: master.')
context.old_commit = fp.string('old', `o`, '', 'A known old commit, required (for it, COMMAND should exit with 0).')
context.command = fp.string('command', `c`, '', 'A command to execute. Should exit with 0 for the *old* commits.')
context.old_commit = fp.string('old', `o`, '',
'A known old commit, required (for it, COMMAND should exit with 0).')
context.command = fp.string('command', `c`, '',
'A command to execute. Should exit with 0 for the *old* commits.')
fp.finalize() or {}
if context.old_commit == '' {
eprintln('--old COMMIT is required')
@@ -55,7 +55,8 @@ fn main() {
n_test_v_files := v_test_files[folder]
if n_v_files > 1 && n_test_v_files == 0 {
println('> ${n_test_v_files:5} _test.v files, with ${n_v_files:5} .v files, in folder: ${folder}')
compilation := os.execute('${os.quoted_path(vexe)} -shared -W -Wfatal-errors -check ${os.quoted_path(folder)}')
compilation :=
os.execute('${os.quoted_path(vexe)} -shared -W -Wfatal-errors -check ${os.quoted_path(folder)}')
if compilation.exit_code != 0 {
eprintln('> ${folder} has parser/checker errors!')
eprintln(compilation.output)
+6 -3
View File
@@ -16,13 +16,15 @@ fn (mut ctx Context) analyze_line(line string, position_file string, position_li
ts := blame_for_time.output.all_after('committer-time').all_before('\n').trim_space().int()
t := time.unix(ts)
if ctx.cut_time < t {
println(term.colorize(term.gray, '>>> SKIPPING since t: ${t} > ${ctx.cut_time}, ${position_file}:${position_line}: ${line}'))
println(term.colorize(term.gray,
'>>> SKIPPING since t: ${t} > ${ctx.cut_time}, ${position_file}:${position_line}: ${line}'))
return
}
ctx.deprecations++
blame_for_context := os.execute('git blame -L${position_line},+5 -- ${position_file}')
context := blame_for_context.output.trim_space().split_into_lines()
println(term.colorize(term.red, '${position_file}:${position_line}: deprecation: ${ctx.deprecations}, timestamp: ${ts} - ${t}'))
println(term.colorize(term.red,
'${position_file}:${position_line}: deprecation: ${ctx.deprecations}, timestamp: ${ts} - ${t}'))
for cline in context {
println(' ${cline}')
}
@@ -42,7 +44,8 @@ fn main() {
all_v_files := os.walk_ext('.', '.v')
for v_file in all_v_files {
if v_file == './vlib/v/fmt/tests/attrs_keep.vv' {
println(term.colorize(term.gray, '>>> SKIPPING deprecations attrs formatting test file ${v_file}'))
println(term.colorize(term.gray,
'>>> SKIPPING deprecations attrs formatting test file ${v_file}'))
continue
}
if v_file.starts_with('./vlib/v/checker/tests') && v_file.contains('deprec') {
+4 -2
View File
@@ -68,7 +68,8 @@ fn create_test(tname string, tcontent string) !string {
fn check_assert_continues_works() ! {
os.chdir(tdir)!
create_test('assert_continues_option_works_test.v', 'fn test_fail1() { assert 2==4\nassert 2==1\nassert 2==0 }\nfn test_ok(){ assert true }\nfn test_fail2() { assert false }')!
create_test('assert_continues_option_works_test.v',
'fn test_fail1() { assert 2==4\nassert 2==1\nassert 2==0 }\nfn test_ok(){ assert true }\nfn test_fail2() { assert false }')!
result := check_fail('${vexe} -assert continues assert_continues_option_works_test.v')
result.has('assert_continues_option_works_test.v:1: fn test_fail1')
result.has('assert_continues_option_works_test.v:2: fn test_fail1')
@@ -76,7 +77,8 @@ fn check_assert_continues_works() ! {
result.has('assert_continues_option_works_test.v:5: fn test_fail2')
result.has('> assert 2 == 4').has('> assert 2 == 1').has('> assert 2 == 0')
// Check if a test function, tagged with [assert_continues], has the same behaviour, without needing additional options
create_test('assert_continues_tag_works_test.v', '@[assert_continues]fn test_fail1() { assert 2==4\nassert 2==1\nassert 2==0 }\nfn test_ok(){ assert true }\nfn test_fail2() { assert false\n assert false }')!
create_test('assert_continues_tag_works_test.v',
'@[assert_continues]fn test_fail1() { assert 2==4\nassert 2==1\nassert 2==0 }\nfn test_ok(){ assert true }\nfn test_fail2() { assert false\n assert false }')!
tag_res := check_fail('${vexe} assert_continues_tag_works_test.v')
tag_res.has('assert_continues_tag_works_test.v:1: fn test_fail1')
tag_res.has('assert_continues_tag_works_test.v:2: fn test_fail1')
+4 -2
View File
@@ -19,7 +19,8 @@ fn main() {
os.mkdir_all(vmodules)!
println('C2V is not installed. Cloning C2V to ${c2v_dir} ...')
os.chdir(vmodules)!
res := os.execute('${os.quoted_path(vexe)} retry -- git clone --filter=blob:none https://github.com/vlang/c2v')
res :=
os.execute('${os.quoted_path(vexe)} retry -- git clone --filter=blob:none https://github.com/vlang/c2v')
if res.exit_code != 0 {
eprintln('Failed to download C2V.')
exit(1)
@@ -29,7 +30,8 @@ fn main() {
if !os.exists(c2v_bin) {
os.chdir(c2v_dir)!
println('Compiling c2v ...')
res2 := os.execute('${os.quoted_path(vexe)} -o ${os.quoted_path(c2v_bin)} -keepc -g -experimental .')
res2 :=
os.execute('${os.quoted_path(vexe)} -o ${os.quoted_path(c2v_bin)} -keepc -g -experimental .')
if res2.exit_code != 0 {
eprintln(res2.output)
eprintln('Failed to compile C2V. This should not happen. Please report it via GitHub.')
+10 -5
View File
@@ -40,13 +40,18 @@ fn main() {
fp.description('Dump a JSON representation of the V AST for a given .v or .vsh file.')
fp.description('By default, `v ast` will save the JSON to a .json file, named after the .v file.')
fp.description('Pass -p to see it instead.')
ctx.is_watch = fp.bool('watch', `w`, false, 'watch a .v file for changes, rewrite the .json file, when a change is detected')
ctx.is_watch = fp.bool('watch', `w`, false,
'watch a .v file for changes, rewrite the .json file, when a change is detected')
ctx.is_print = fp.bool('print', `p`, false, 'print the AST to stdout')
ctx.is_compile = fp.bool('compile', `c`, false, 'watch the .v file for changes, rewrite the .json file, *AND* generate a .c file too on any change')
ctx.is_terse = fp.bool('terse', `t`, false, 'terse output, only with tree node names (AST structure), no details')
ctx.is_skip_defaults = fp.bool('skip-defaults', `s`, false, 'skip properties that have default values like false, 0, "", etc')
ctx.is_compile = fp.bool('compile', `c`, false,
'watch the .v file for changes, rewrite the .json file, *AND* generate a .c file too on any change')
ctx.is_terse = fp.bool('terse', `t`, false,
'terse output, only with tree node names (AST structure), no details')
ctx.is_skip_defaults = fp.bool('skip-defaults', `s`, false,
'skip properties that have default values like false, 0, "", etc')
ctx.check = fp.bool('check', `k`, false, 'run v.checker as well (it may modify the AST)')
hfields := fp.string_multi('hide', 0, 'hide the specified fields. You can give several, by separating them with `,`').join(',')
hfields := fp.string_multi('hide', 0,
'hide the specified fields. You can give several, by separating them with `,`').join(',')
for hf in hfields.split(',') {
ctx.hide_names[hf] = true
}
+2 -1
View File
@@ -98,7 +98,8 @@ fn main() {
context.show_help = fp.bool('help', `h`, false, 'Show this help screen.')
context.module_name = fp.string('module', `m`, 'binary', 'Name of the generated module.')
context.prefix = fp.string('prefix', `p`, '', 'A prefix put before each resource name.')
context.write_file = fp.string('write', `w`, '', 'Write directly to a file with the given name.')
context.write_file = fp.string('write', `w`, '',
'Write directly to a file with the given name.')
if context.show_help {
println(fp.usage())
exit(0)
+6 -3
View File
@@ -57,7 +57,8 @@ fn get_v_build_output(is_verbose bool, is_yes bool, file_path string, user_args
elog('> unable to compile V in debug mode: ${result.output}\ncommand: ${vdbg_compilation_cmd}\n')
}
result = runv('Compile', '${os.quoted_path(vexe)} ${verbose_flag} ${user_args} ${os.quoted_path(file_path)}')
result = runv('Compile',
'${os.quoted_path(vexe)} ${verbose_flag} ${user_args} ${os.quoted_path(file_path)}')
defer {
os.rm(vdbg_path) or {
if is_verbose {
@@ -185,11 +186,13 @@ ${build_output}```
${expected_result}
'
mut encoded_body := urllib.query_escape(raw_body.replace_once('{file_content}', '```v\n${file_content}\n```'))
mut encoded_body := urllib.query_escape(raw_body.replace_once('{file_content}',
'```v\n${file_content}\n```'))
mut generated_uri := 'https://github.com/vlang/v/issues/new?labels=Bug&body=${encoded_body}'
if generated_uri.len > 8192 {
// GitHub doesn't support URLs longer than 8192 characters
encoded_body = urllib.query_escape(raw_body.replace_once('{file_content}', 'See attached file `${file_path}`'))
encoded_body = urllib.query_escape(raw_body.replace_once('{file_content}',
'See attached file `${file_path}`'))
generated_uri = 'https://github.com/vlang/v/issues/new?labels=Bug&body=${encoded_body}'
elog('> Your file is too big to be submitted.')
elog('> Go to the following URL, and attach your file:')
+44 -22
View File
@@ -400,17 +400,21 @@ fn (mut f MDFile) check() CheckResult {
if !f.skip_line_length_check {
ctx := CheckResultContext{f.path, j, line}
if f.state == .vexample {
f.wcheck(line.len, too_long_line_length_example, ctx, 'example lines must be less than @ characters')
f.wcheck(line.len, too_long_line_length_example, ctx,
'example lines must be less than @ characters')
} else if f.state == .codeblock {
f.wcheck(line.len, too_long_line_length_codeblock, ctx, 'code lines must be less than @ characters')
f.wcheck(line.len, too_long_line_length_codeblock, ctx,
'code lines must be less than @ characters')
} else if line.starts_with('|') {
f.wcheck(line.len, too_long_line_length_table, ctx, 'table lines must be less than @ characters')
f.wcheck(line.len, too_long_line_length_table, ctx,
'table lines must be less than @ characters')
} else if line.contains('http') {
// vfmt off
f.wcheck(line.all_after('https').len, too_long_line_length_link, ctx, 'link lines must be less than @ characters')
// vfmt on
} else {
f.echeck(line.len, too_long_line_length_other, ctx, 'must be less than @ characters')
f.echeck(line.len, too_long_line_length_other, ctx,
'must be less than @ characters')
}
}
if f.state == .markdown {
@@ -557,14 +561,16 @@ fn (mut f MDFile) check_link_target_match(ad AnchorData) {
found_error_warning = true
f.errors++
for anchordata in ad.anchors[link] {
eprintln(eline(f.path, anchordata.line, 0, 'multiple link targets of existing link (#${link})'))
eprintln(eline(f.path, anchordata.line, 0,
'multiple link targets of existing link (#${link})'))
}
}
} else {
found_error_warning = true
f.errors++
for brokenlink in linkdata {
eprintln(eline(f.path, brokenlink.line, 0, 'no link target found for existing link [${brokenlink.label}](#${link})'))
eprintln(eline(f.path, brokenlink.line, 0,
'no link target found for existing link [${brokenlink.label}](#${link})'))
}
}
}
@@ -580,7 +586,8 @@ fn (mut f MDFile) check_link_target_match(ad AnchorData) {
anchor.line
}
}
wprintln(wline(f.path, line, 0, 'multiple link target for non existing link (#${link})'))
wprintln(wline(f.path, line, 0,
'multiple link target for non existing link (#${link})'))
found_error_warning = true
f.warnings++
}
@@ -657,8 +664,10 @@ fn (mut f MDFile) check_examples() {
fname := os.base(f.path).replace('.md', '_md')
uid := rand.ulid()
cfile := os.join_path(vcheckfolder, '${uid}.c')
vfile := os.join_path(vcheckfolder, 'check_${fname}_example_${e.sline}__${e.eline}__${uid}.v')
efile := os.join_path(vcheckfolder, 'check_${fname}_example_${e.sline}__${e.eline}__${uid}.exe')
vfile := os.join_path(vcheckfolder,
'check_${fname}_example_${e.sline}__${e.eline}__${uid}.v')
efile := os.join_path(vcheckfolder,
'check_${fname}_example_${e.sline}__${e.eline}__${uid}.exe')
mut should_cleanup_vfile := true
// eprintln('>>> checking example ${vfile} ...')
vcontent := e.text.join('\n') + '\n'
@@ -672,7 +681,8 @@ fn (mut f MDFile) check_examples() {
f.ferrors += fmt_res
match command {
'compile' {
res := cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -o ${os.quoted_path(efile)} ${os.quoted_path(vfile)}')
res :=
cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -o ${os.quoted_path(efile)} ${os.quoted_path(vfile)}')
if res != 0 || fmt_res != 0 {
if res != 0 {
eprintln(eline(f.path, e.sline, 0, 'example failed to compile'))
@@ -690,7 +700,8 @@ fn (mut f MDFile) check_examples() {
f.oks++
}
'cgen' {
res := cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -o ${os.quoted_path(cfile)} ${os.quoted_path(vfile)}')
res :=
cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -o ${os.quoted_path(cfile)} ${os.quoted_path(vfile)}')
if res != 0 || fmt_res != 0 {
if res != 0 {
eprintln(eline(f.path, e.sline, 0, 'example failed to generate C code'))
@@ -708,10 +719,12 @@ fn (mut f MDFile) check_examples() {
f.oks++
}
'globals' {
res := cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -enable-globals -o ${os.quoted_path(cfile)} ${os.quoted_path(vfile)}')
res :=
cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -enable-globals -o ${os.quoted_path(cfile)} ${os.quoted_path(vfile)}')
if res != 0 || fmt_res != 0 {
if res != 0 {
eprintln(eline(f.path, e.sline, 0, '`example failed to compile with -enable-globals'))
eprintln(eline(f.path, e.sline, 0,
'`example failed to compile with -enable-globals'))
}
f.report_not_formatted_example_if_needed(e, fmt_res, vfile) or {
unsafe {
@@ -726,10 +739,12 @@ fn (mut f MDFile) check_examples() {
f.oks++
}
'live' {
res := cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -live -o ${os.quoted_path(cfile)} ${os.quoted_path(vfile)}')
res :=
cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -live -o ${os.quoted_path(cfile)} ${os.quoted_path(vfile)}')
if res != 0 || fmt_res != 0 {
if res != 0 {
eprintln(eline(f.path, e.sline, 0, 'example failed to compile with -live'))
eprintln(eline(f.path, e.sline, 0,
'example failed to compile with -live'))
}
f.report_not_formatted_example_if_needed(e, fmt_res, vfile) or {
unsafe {
@@ -744,10 +759,12 @@ fn (mut f MDFile) check_examples() {
f.oks++
}
'shared' {
res := cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -shared -o ${os.quoted_path(cfile)} ${os.quoted_path(vfile)}')
res :=
cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -shared -o ${os.quoted_path(cfile)} ${os.quoted_path(vfile)}')
if res != 0 || fmt_res != 0 {
if res != 0 {
eprintln(eline(f.path, e.sline, 0, 'module example failed to compile with -shared'))
eprintln(eline(f.path, e.sline, 0,
'module example failed to compile with -shared'))
}
f.report_not_formatted_example_if_needed(e, fmt_res, vfile) or {
unsafe {
@@ -762,7 +779,8 @@ fn (mut f MDFile) check_examples() {
f.oks++
}
'failcompile' {
res := silent_cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -o ${os.quoted_path(cfile)} ${os.quoted_path(vfile)}')
res :=
silent_cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -o ${os.quoted_path(cfile)} ${os.quoted_path(vfile)}')
if res == 0 || fmt_res != 0 {
if res == 0 {
eprintln(eline(f.path, e.sline, 0, '`failcompile` example compiled'))
@@ -780,10 +798,12 @@ fn (mut f MDFile) check_examples() {
f.oks++
}
'oksyntax' {
res := cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -check-syntax ${os.quoted_path(vfile)}')
res :=
cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -check-syntax ${os.quoted_path(vfile)}')
if res != 0 || fmt_res != 0 {
if res != 0 {
eprintln(eline(f.path, e.sline, 0, '`oksyntax` example with invalid syntax'))
eprintln(eline(f.path, e.sline, 0,
'`oksyntax` example with invalid syntax'))
}
f.report_not_formatted_example_if_needed(e, fmt_res, vfile) or {
unsafe {
@@ -812,7 +832,8 @@ fn (mut f MDFile) check_examples() {
f.oks++
}
'badsyntax' {
res := silent_cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -check-syntax ${os.quoted_path(vfile)}')
res :=
silent_cmdexecute('${os.quoted_path(vexe)} -w -Wfatal-errors -check-syntax ${os.quoted_path(vfile)}')
if res == 0 {
eprintln(eline(f.path, e.sline, 0, '`badsyntax` example can be parsed fine'))
eprintln(vcontent)
@@ -830,7 +851,8 @@ fn (mut f MDFile) check_examples() {
// when ```vmod
'mod' {}
else {
eprintln(eline(f.path, e.sline, 0, 'unrecognized command: "${command}", use one of: wip/ignore/compile/failcompile/okfmt/nofmt/oksyntax/badsyntax/cgen/globals/live/shared'))
eprintln(eline(f.path, e.sline, 0,
'unrecognized command: "${command}", use one of: wip/ignore/compile/failcompile/okfmt/nofmt/oksyntax/badsyntax/cgen/globals/live/shared'))
should_cleanup_vfile = false
f.errors++
}
+19 -18
View File
@@ -87,8 +87,8 @@ fn test_check_md_respects_vcheckignore_glob_in_scanned_dir() {
write_text_file(os.join_path(repo_dir, 'doc', 'plans', 'keep3.md'), '# keep\n')!
write_text_file(os.join_path(repo_dir, 'doc', 'plans', '.vcheckignore'), 'ignored*.md\n')!
res := run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent doc/plans',
true)!
res := run_in_dir(repo_dir,
'${os.quoted_path(vexe)} check-md -hide-warnings -silent doc/plans', true)!
assert res.exit_code == 0, res.output
assert res.output.contains('SKIP: doc/plans/ignored1.md'), res.output
assert res.output.contains('SKIP: doc/plans/ignored2.md'), res.output
@@ -119,8 +119,8 @@ fn test_check_md_respects_vcheckignore_anchored_pattern() {
write_text_file(os.join_path(repo_dir, 'docs', 'keep.md'), '# keep\n')!
write_text_file(os.join_path(repo_dir, 'docs', '.vcheckignore'), '/root_only.md\n')!
res := run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent docs',
true)!
res :=
run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent docs', true)!
assert res.exit_code == 0, res.output
assert res.output.contains('SKIP: docs/root_only.md'), res.output
assert res.output.contains('from docs/.vcheckignore: /root_only.md'), res.output
@@ -150,8 +150,8 @@ fn test_check_md_respects_vcheckignore_anchored_directory_pattern() {
write_text_file(os.join_path(repo_dir, 'docs', 'keep.md'), '# keep\n')!
write_text_file(os.join_path(repo_dir, 'docs', '.vcheckignore'), '/sub/\n')!
res := run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent docs',
true)!
res :=
run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent docs', true)!
assert res.exit_code == 0, res.output
assert res.output.contains('SKIP: docs/sub/ignored.md'), res.output
assert res.output.contains('from docs/.vcheckignore: /sub/'), res.output
@@ -181,8 +181,8 @@ fn test_check_md_respects_vcheckignore_non_anchored_directory_pattern() {
write_text_file(os.join_path(repo_dir, 'docs', 'keep.md'), '# keep\n')!
write_text_file(os.join_path(repo_dir, 'docs', '.vcheckignore'), 'sub/\n')!
res := run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent docs',
true)!
res :=
run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent docs', true)!
assert res.exit_code == 0, res.output
assert res.output.contains('SKIP: docs/sub/ignored1.md'), res.output
assert res.output.contains('SKIP: docs/nested/sub/ignored2.md'), res.output
@@ -212,8 +212,7 @@ fn test_check_md_respects_vcheckignore_anchored_directory_glob_pattern() {
write_text_file(os.join_path(repo_dir, 'other', 'keep.md'), '# keep\n')!
write_text_file(os.join_path(repo_dir, '.vcheckignore'), '/docs-*/\n')!
res := run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent .',
true)!
res := run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent .', true)!
assert res.exit_code == 0, res.output
assert res.output.contains('SKIP: docs-a/sub/ignored1.md'), res.output
assert res.output.contains('SKIP: docs-b/sub/ignored2.md'), res.output
@@ -242,10 +241,11 @@ fn test_check_md_respects_vcheckignore_comments_and_blank_lines() {
write_text_file(os.join_path(repo_dir, 'docs', 'ignored.md'), '# ignored\n')!
write_text_file(os.join_path(repo_dir, 'docs', 'ignored2.md'), '# ignored2\n')!
write_text_file(os.join_path(repo_dir, 'docs', 'keep.md'), '# keep\n')!
write_text_file(os.join_path(repo_dir, 'docs', '.vcheckignore'), '# comment\n\nignored.md # inline comment\nignored2.md\n')!
write_text_file(os.join_path(repo_dir, 'docs', '.vcheckignore'),
'# comment\n\nignored.md # inline comment\nignored2.md\n')!
res := run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent docs',
true)!
res :=
run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent docs', true)!
assert res.exit_code == 0, res.output
assert res.output.contains('SKIP: docs/ignored.md'), res.output
assert res.output.contains('SKIP: docs/ignored2.md'), res.output
@@ -275,8 +275,8 @@ fn test_check_md_file_argument_does_not_use_vcheckignore_directory_filtering() {
write_text_file(os.join_path(repo_dir, 'docs', 'ignored.md'), '# ignored by dir scan\n')!
write_text_file(os.join_path(repo_dir, 'docs', '.vcheckignore'), 'ignored.md\n')!
res := run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent docs/ignored.md',
true)!
res := run_in_dir(repo_dir,
'${os.quoted_path(vexe)} check-md -hide-warnings -silent docs/ignored.md', true)!
assert res.exit_code == 0, res.output
assert !res.output.contains('SKIP: docs/ignored.md'), res.output
assert res.output.contains('> Found: 1 .md files.'), res.output
@@ -303,7 +303,8 @@ fn test_check_md_uses_scanned_dir_repo_root_for_vcheckignore() {
os.execute_or_exit('${os.quoted_path(git_exe)} init ${os.quoted_path(repo_b)}')
write_text_file(os.join_path(base_dir, '.vcheckignore'), 'outside*.md\n')!
write_text_file(os.join_path(repo_b, 'docs', 'outside1.md'), '# outside but should not be skipped\n')!
write_text_file(os.join_path(repo_b, 'docs', 'outside1.md'),
'# outside but should not be skipped\n')!
write_text_file(os.join_path(repo_b, 'docs', 'keep1.md'), '# keep\n')!
res := run_in_dir(repo_a, '${os.quoted_path(vexe)} check-md -hide-warnings -silent ${os.quoted_path(os.join_path(repo_b,
@@ -336,8 +337,8 @@ fn test_check_md_multiple_directories_accumulate_skipped_count() {
write_text_file(os.join_path(repo_dir, 'notes', 'keep.md'), '# keep\n')!
write_text_file(os.join_path(repo_dir, '.vcheckignore'), 'docs/ignored.md\nnotes/ignored.md\n')!
res := run_in_dir(repo_dir, '${os.quoted_path(vexe)} check-md -hide-warnings -silent docs notes',
true)!
res := run_in_dir(repo_dir,
'${os.quoted_path(vexe)} check-md -hide-warnings -silent docs notes', true)!
assert res.exit_code == 0, res.output
assert res.output.contains('SKIP: docs/ignored.md'), res.output
assert res.output.contains('SKIP: notes/ignored.md'), res.output
+2 -1
View File
@@ -684,7 +684,8 @@ fn auto_complete_request(args []string) []string {
add_sep := if part == '~' { os.path_separator } else { '' }
part = part.replace_once('~', os.home_dir().trim_right(os.path_separator)) + add_sep
}
is_abs_path := part.starts_with(os.path_separator) // TODO: Windows support for drive prefixes
is_abs_path :=
part.starts_with(os.path_separator) // TODO: Windows support for drive prefixes
if part.ends_with(os.path_separator) || part == '.' || part == '..' {
// 'v <command>(.*/$|.|..)<tab>' -> output full directory list
ls_path = '.' + os.path_separator + part
+12 -6
View File
@@ -43,7 +43,8 @@ fn test_simple() {
assert !os.exists(t2), t2
assert !os.exists(t3), t3
r1 := execute('${os.quoted_path(vexe)} -no-skip-unused -coverage ${os.quoted_path(t1)} cmd/tools/vcover/testdata/simple/t1_test.v')
r1 :=
execute('${os.quoted_path(vexe)} -no-skip-unused -coverage ${os.quoted_path(t1)} cmd/tools/vcover/testdata/simple/t1_test.v')
assert r1.exit_code == 0, r1.str()
assert r1.output.trim_space() == '10', r1.str()
assert os.exists(t1), t1
@@ -52,7 +53,8 @@ fn test_simple() {
assert filter1.exit_code == 0, filter1.output
assert filter1.output.contains('cmd/tools/vcover/testdata/simple/simple.v'), filter1.output
assert filter1.output.trim_space().ends_with('| 4 | 9 | 44.44%'), filter1.output
hfilter1 := execute('${os.quoted_path(vexe)} cover ${os.quoted_path(t1)} --filter vcover/testdata/simple/ -H -P false')
hfilter1 :=
execute('${os.quoted_path(vexe)} cover ${os.quoted_path(t1)} --filter vcover/testdata/simple/ -H -P false')
assert hfilter1.exit_code == 0, hfilter1.output
assert !hfilter1.output.contains('%'), hfilter1.output
houtput1 := hfilter1.output.trim_space().split_into_lines()
@@ -70,15 +72,18 @@ fn test_simple() {
assert nzeros1.any(it.contains('simple.v:8')), nzeros1.str()
assert nzeros1.any(it.contains('simple.v:25')), nzeros1.str()
r2 := execute('${os.quoted_path(vexe)} -no-skip-unused -coverage ${os.quoted_path(t2)} cmd/tools/vcover/testdata/simple/t2_test.v')
r2 :=
execute('${os.quoted_path(vexe)} -no-skip-unused -coverage ${os.quoted_path(t2)} cmd/tools/vcover/testdata/simple/t2_test.v')
assert r2.exit_code == 0, r2.str()
assert r2.output.trim_space() == '24', r2.str()
assert os.exists(t2), t2
filter2 := execute('${os.quoted_path(vexe)} cover ${os.quoted_path(t2)} --filter vcover/testdata/simple')
filter2 :=
execute('${os.quoted_path(vexe)} cover ${os.quoted_path(t2)} --filter vcover/testdata/simple')
assert filter2.exit_code == 0, filter2.output
assert filter2.output.contains('cmd/tools/vcover/testdata/simple/simple.v')
assert filter2.output.trim_space().ends_with('| 6 | 9 | 66.67%'), filter2.output
hfilter2 := execute('${os.quoted_path(vexe)} cover ${os.quoted_path(t2)} --filter testdata/simple -H -P false')
hfilter2 :=
execute('${os.quoted_path(vexe)} cover ${os.quoted_path(t2)} --filter testdata/simple -H -P false')
assert hfilter2.exit_code == 0, hfilter2.output
assert !hfilter2.output.contains('%'), hfilter2.output
houtput2 := hfilter2.output.trim_space().split_into_lines()
@@ -95,7 +100,8 @@ fn test_simple() {
assert nzeros2.any(it.contains('simple.v:25')), nzeros2.str()
// Run both tests. The coverage should be combined and == 100%
r3 := execute('${os.quoted_path(vexe)} -no-skip-unused -coverage ${os.quoted_path(t3)} test cmd/tools/vcover/testdata/simple/')
r3 :=
execute('${os.quoted_path(vexe)} -no-skip-unused -coverage ${os.quoted_path(t3)} test cmd/tools/vcover/testdata/simple/')
assert r3.exit_code == 0, r3.str()
assert r3.output.trim_space().contains('Summary for all V _test.v files: '), r3.str()
assert os.exists(t3), t3
+8 -4
View File
@@ -158,11 +158,15 @@ fn main() {
fp.arguments_description('[folder1/ file2 ...]')
fp.skip_executable()
ctx.show_help = fp.bool('help', `h`, false, 'Show this help text.')
ctx.be_verbose = fp.bool('verbose', `v`, false, 'Be more verbose while processing the coverages.')
ctx.show_hotspots = fp.bool('hotspots', `H`, false, 'Show most frequently executed covered lines.')
ctx.be_verbose = fp.bool('verbose', `v`, false,
'Be more verbose while processing the coverages.')
ctx.show_hotspots = fp.bool('hotspots', `H`, false,
'Show most frequently executed covered lines.')
ctx.show_percentages = fp.bool('percentages', `P`, true, 'Show coverage percentage per file.')
ctx.show_test_files = fp.bool('show_test_files', `S`, false, 'Show `_test.v` files as well (normally filtered).')
ctx.use_absolute_paths = fp.bool('absolute', `A`, false, 'Use absolute paths for all files, no matter the current folder. By default, files inside the current folder, are shown with a relative path.')
ctx.show_test_files = fp.bool('show_test_files', `S`, false,
'Show `_test.v` files as well (normally filtered).')
ctx.use_absolute_paths = fp.bool('absolute', `A`, false,
'Use absolute paths for all files, no matter the current folder. By default, files inside the current folder, are shown with a relative path.')
ctx.filter = fp.string('filter', `f`, '', 'Filter only the matching source path patterns.')
if ctx.show_help {
println(fp.usage())
+1 -1
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env expect
set timeout 3
set timeout 10
# Pass v_root as arg, since we chdir into a temp directory during testing and create a project there.
set v_root [lindex $argv 0]
@@ -1,6 +1,6 @@
#!/usr/bin/env expect
set timeout 3
set timeout 10
# Pass v_root as arg, since we chdir into a temp directory during testing and create a project there.
set v_root [lindex $argv 0]
@@ -1,6 +1,6 @@
#!/usr/bin/env expect
set timeout 3
set timeout 10
# Pass v_root as arg, since we chdir into a temp directory during testing and create a project there.
set v_root [lindex $argv 0]
@@ -1,6 +1,6 @@
#!/usr/bin/env expect
set timeout 3
set timeout 10
# Pass v_root as arg, since we chdir into a temp directory during testing and create a project there.
set v_root [lindex $argv 0]
@@ -1,6 +1,6 @@
#!/usr/bin/env expect
set timeout 3
set timeout 10
# Pass v_root as arg, since we chdir into a temp directory during testing and create a project there.
set v_root [lindex $argv 0]
@@ -1,6 +1,6 @@
#!/usr/bin/env expect
set timeout 3
set timeout 10
# Pass v_root as arg, since we chdir into a temp directory during testing and create a project there.
set v_root [lindex $argv 0]
+6 -3
View File
@@ -150,7 +150,8 @@ indent_style = tab
prepare_test_path()!
os.write_file('.gitattributes', git_attributes_content)!
os.write_file('.editorconfig', editor_config_content)!
res := os.execute_or_exit('${expect_exe} ${os.join_path(expect_tests_path, 'init.expect')} ${vroot}')
res :=
os.execute_or_exit('${expect_exe} ${os.join_path(expect_tests_path, 'init.expect')} ${vroot}')
assert res.output.contains('Created binary (application) project `${test_project_dir_name}`')
assert os.read_file('.gitattributes')! == git_attributes_content
assert os.read_file('.editorconfig')! == editor_config_content
@@ -163,7 +164,8 @@ fn test_v_init_in_dir_with_invalid_mod_name_input() {
proj_path := os.join_path(os.vtmp_dir(), dir_name_with_invalid_mod_name)
os.mkdir_all(proj_path) or {}
os.chdir(proj_path)!
os.execute_or_exit('${expect_exe} ${os.join_path(expect_tests_path, 'init_in_dir_with_invalid_mod_name.expect')} ${vroot} ${dir_name_with_invalid_mod_name} ${corrected_mod_name}')
os.execute_or_exit('${expect_exe} ${os.join_path(expect_tests_path,
'init_in_dir_with_invalid_mod_name.expect')} ${vroot} ${dir_name_with_invalid_mod_name} ${corrected_mod_name}')
// Assert mod data set in `new_with_model_arg.expect`.
mod := vmod.from_file(os.join_path(proj_path, 'v.mod')) or {
assert false, err.str()
@@ -175,7 +177,8 @@ fn test_v_init_in_dir_with_invalid_mod_name_input() {
fn test_v_init_with_model_arg_input() {
prepare_test_path()!
model := '--lib'
res := os.execute_or_exit('${expect_exe} ${os.join_path(expect_tests_path, 'init_with_model_arg.expect')} ${vroot} ${model}')
res := os.execute_or_exit('${expect_exe} ${os.join_path(expect_tests_path,
'init_with_model_arg.expect')} ${vroot} ${model}')
assert res.output.contains('Created library project `${test_project_dir_name}`'), res.output
project_path := os.join_path(test_path)
mod := vmod.from_file(os.join_path(project_path, 'v.mod')) or {
@@ -40,6 +40,5 @@ fn test_get_parent_mod_normal_cases() {
assert get_parent_mod(os.join_path(@VMODROOT, 'vlib', 'v', 'token'))! == 'v'
assert get_parent_mod(os.join_path(@VMODROOT, 'vlib', 'os', 'os.v'))! == 'os'
assert get_parent_mod(os.join_path(@VMODROOT, 'cmd'))! == ''
assert get_parent_mod(os.join_path(@VMODROOT, 'cmd', 'tools', 'modules', 'testing',
'common.v'))! == 'tools.modules.testing'
assert get_parent_mod(os.join_path(@VMODROOT, 'cmd', 'tools', 'modules', 'testing', 'common.v'))! == 'tools.modules.testing'
}
+3 -1
View File
@@ -67,7 +67,9 @@ fn color_highlight(code string, tb &ast.Table) string {
}
return lit
}
mut s := scanner.new_scanner(code, .parse_comments, &pref.Preferences{ is_fmt: true })
mut s := scanner.new_scanner(code, .parse_comments, &pref.Preferences{
is_fmt: true
})
mut prev_prev := token.Token{}
mut prev := token.Token{}
mut tok := s.scan()
+8 -3
View File
@@ -64,7 +64,8 @@ fn (vd &VDoc) render_search_index(out Output) {
for i, title in vd.search_module_index {
data := vd.search_module_data[i]
js_search_index.write_string('"${title}",\n')
description := data.description.replace('\n', '').replace('\r', '') // fix multiline js string bug
description :=
data.description.replace('\n', '').replace('\r', '') // fix multiline js string bug
js_search_data.write_string('["${description}","${data.link}"],\n')
}
js_search_index.writeln('];\n')
@@ -191,6 +192,7 @@ fn (vd &VDoc) write_content(cn &doc.DocNode, d &doc.Doc, mut hw strings.Builder)
cfg := vd.cfg
file_path_name := vd.get_repo_file_path_for_links(cn.file_path)
src_link := get_src_link(vd.manifest.repo_url, vd.manifest.repo_branch, file_path_name,
cn.pos.line_nr + 1)
md_link_base := get_src_dir_link(vd.manifest.repo_url, vd.manifest.repo_branch, file_path_name)
if cn.content.len != 0 || cn.name == 'Constants' {
@@ -510,7 +512,9 @@ fn write_token(tok token.Token, typ HighlightTokenTyp, mut buf strings.Builder)
}
fn html_highlight(code string, tb &ast.Table) string {
mut s := scanner.new_scanner(code, .parse_comments, &pref.Preferences{ output_mode: .silent })
mut s := scanner.new_scanner(code, .parse_comments, &pref.Preferences{
output_mode: .silent
})
mut tok := s.scan()
mut prev_tok := tok
mut next_tok := s.scan()
@@ -697,7 +701,8 @@ fn (vd &VDoc) doc_node_html(dn doc.DocNode, link string, md_link_base string, he
dnw.write_string('</div>\n')
}
if deprecated_tags.len > 0 {
attributes := deprecated_tags.map('<div class="attribute attribute-deprecated">${it.replace_each(quote_escape_seq)}</div>\n').join('')
attributes :=
deprecated_tags.map('<div class="attribute attribute-deprecated">${it.replace_each(quote_escape_seq)}</div>\n').join('')
dnw.writeln('<div class="attributes">${attributes}</div>\n')
}
if tags.len > 0 {
+2 -1
View File
@@ -75,7 +75,8 @@ fn (mut vd VDoc) run_examples(dn doc.DocNode) {
cmd := '${os.quoted_path(vexe)} ${voptions} ${os.quoted_path(vsource_path)}'
res := os.execute(cmd)
if res.exit_code != 0 {
eprintln('${dn_to_location(dn)}:${term.ecolorize(term.red, 'error in documentation example')}')
eprintln('${dn_to_location(dn)}:${term.ecolorize(term.red,
'error in documentation example')}')
eprintln(' cmd: ${cmd}')
eprintln(' example line: ${term.colorize(term.bright_yellow, example)}')
eprintln(' result:')
+2 -1
View File
@@ -245,7 +245,8 @@ fn (vd &VDoc) get_readme(path string) Readme {
mut readme_frontmatter := map[string]string{}
if readme_contents.starts_with('---\n') {
if frontmatter_lines_end_idx := readme_contents.index('\n---\n') {
front_matter_lines := readme_contents#[4..frontmatter_lines_end_idx].trim_space().split_into_lines()
front_matter_lines :=
readme_contents#[4..frontmatter_lines_end_idx].trim_space().split_into_lines()
for line in front_matter_lines {
x := line.split(': ')
if x.len == 2 {
+4 -2
View File
@@ -27,14 +27,16 @@ fn test_output() {
should_sort: false
)
fails += check_output('${vexe} doc -comments ${qpath}', '${path_no_ext}.comments.out')
fails += check_output('${vexe} doc -readme -comments ${qpath}', '${path_no_ext}.readme.comments.out')
fails += check_output('${vexe} doc -readme -comments ${qpath}',
'${path_no_ext}.readme.comments.out')
// test the main 3 different formats:
program_dir := os.quoted_path(if os.is_dir(path) { path } else { os.dir(path) })
for fmt in ['html', 'ansi', 'text'] {
fails += check_output('${vexe} doc -no-timestamp -f ${fmt} -o - -html-only-contents -readme -comments ${program_dir}',
'${path_no_ext}.${fmt}')
}
fails += check_output('${vexe} doc -no-timestamp -f md -o - ${program_dir}', '${path_no_ext}.md')
fails += check_output('${vexe} doc -no-timestamp -f md -o - ${program_dir}',
'${path_no_ext}.md')
if fails == 0 {
println(term.green('OK'))
} else {
+16 -8
View File
@@ -36,16 +36,24 @@ fn main() {
fp.skip_executable()
fp.limit_free_args_to_at_least(1)!
ctx.show_help = fp.bool('help', `h`, false, 'Show this help screen.')
ctx.target_folder = fp.string('target-folder', `t`, '.', 'The target folder, where the file will be stored. It will be created, if it does not exist. Default is current folder.')
ctx.output = fp.string('output', `o`, '', 'Write output to the given file, instead of inferring it from the final part of the URL. All intermediate folders will be created, if they do not exist.')
ctx.target_folder = fp.string('target-folder', `t`, '.',
'The target folder, where the file will be stored. It will be created, if it does not exist. Default is current folder.')
ctx.output = fp.string('output', `o`, '',
'Write output to the given file, instead of inferring it from the final part of the URL. All intermediate folders will be created, if they do not exist.')
ctx.show_sha1 = fp.bool('sha1', `1`, false, 'Show the SHA1 hash of the downloaded file.')
ctx.show_sha256 = fp.bool('sha256', `2`, false, 'Show the SHA256 hash of the downloaded file.')
ctx.show_sha3_256 = fp.bool('sha3-256', `3`, false, 'Show the SHA3-256 (Keccak) hash of the downloaded file.')
ctx.continue_on_failure = fp.bool('continue', `c`, false, 'Continue on download failures. If you download 5 URLs, and several of them fail, continue without error. False by default.')
ctx.retries = fp.int('retries', `r`, 10, 'Number of retries, when an URL fails to download. The default is 10.')
ctx.delay = time.Duration(u64(fp.float('delay', `d`, 1.0, 'Delay in seconds, after each retry. The default is 1 second.') * time.second))
ctx.should_run = fp.bool('run', `R`, false, 'Run, after the script/program is completely downloaded.')
ctx.delete_after_run = fp.bool('delete-after-run', `D`, false, 'Delete the downloaded script/program, after it has been run.')
ctx.show_sha3_256 = fp.bool('sha3-256', `3`, false,
'Show the SHA3-256 (Keccak) hash of the downloaded file.')
ctx.continue_on_failure = fp.bool('continue', `c`, false,
'Continue on download failures. If you download 5 URLs, and several of them fail, continue without error. False by default.')
ctx.retries = fp.int('retries', `r`, 10,
'Number of retries, when an URL fails to download. The default is 10.')
ctx.delay = time.Duration(u64(fp.float('delay', `d`, 1.0,
'Delay in seconds, after each retry. The default is 1 second.') * time.second))
ctx.should_run = fp.bool('run', `R`, false,
'Run, after the script/program is completely downloaded.')
ctx.delete_after_run = fp.bool('delete-after-run', `D`, false,
'Delete the downloaded script/program, after it has been run.')
if ctx.show_help {
println(fp.usage())
exit(0)
-18
View File
@@ -232,19 +232,6 @@ fn (foptions &FormatOptions) format_pipe() {
foptions.vlog('fmt.fmt worked and ${formatted_content.len} bytes were written to stdout.')
}
fn print_compiler_options(compiler_params &pref.Preferences) {
eprintln(' os: ' + compiler_params.os.str())
eprintln(' ccompiler: ${compiler_params.ccompiler}')
eprintln(' path: ${compiler_params.path} ')
eprintln(' out_name: ${compiler_params.out_name} ')
eprintln(' vroot: ${compiler_params.vroot} ')
eprintln('lookup_path: ${compiler_params.lookup_path} ')
eprintln(' out_name: ${compiler_params.out_name} ')
eprintln(' cflags: ${compiler_params.cflags} ')
eprintln(' is_test: ${compiler_params.is_test} ')
eprintln(' is_script: ${compiler_params.is_script} ')
}
fn (mut foptions FormatOptions) post_process_file(file string, formatted_file_path string) ! {
if formatted_file_path == '' {
return
@@ -310,11 +297,6 @@ fn (mut foptions FormatOptions) post_process_file(file string, formatted_file_pa
flush_stdout()
}
fn read_source_lines(file string) ![]string {
source_lines := os.read_lines(file) or { return error('can not read ${file}') }
return source_lines
}
@[noreturn]
fn verror(s string) {
util.verror('vfmt error', s)
+22 -11
View File
@@ -163,11 +163,13 @@ fn main() {
// Collect tool options
mut opt := Options{
verbose: fp.bool('verbose', `v`, false, "Be verbose about the tool's progress.")
compare_only: fp.bool('compare-only', `c`, false, "Don't generate screenshots - only compare input directories")
compare_only: fp.bool('compare-only', `c`, false,
"Don't generate screenshots - only compare input directories")
root_path: fp.string('root-path', `r`, v_root, 'Root path of the comparison')
}
toml_conf := fp.string('toml-config', `t`, default_toml, 'Path or string with TOML configuration')
toml_conf := fp.string('toml-config', `t`, default_toml,
'Path or string with TOML configuration')
arg_paths := fp.finalize()!
if show_help {
println(fp.usage())
@@ -230,7 +232,8 @@ fn generate_screenshots(mut opt Options, output_path string) ! {
if app_config.capture.method == 'gg_record' {
opt.verbose_eprintln('Compiling shaders (if needed) for `${file}`')
sh_result := opt.verbose_execute('${os.quoted_path(v_exe)} shader ${os.quoted_path(app_path)}')
sh_result :=
opt.verbose_execute('${os.quoted_path(v_exe)} shader ${os.quoted_path(app_path)}')
if sh_result.exit_code != 0 {
opt.verbose_eprintln('Skipping shader compile for `${file}` v shader failed with:\n${sh_result.output}')
continue
@@ -339,7 +342,8 @@ fn take_screenshots(opt Options, app AppConfig) ![]string {
}
flags := app.capture.flags.join(' ')
result := opt.verbose_execute('${os.quoted_path(v_exe)} ${flags} -d gg_record run ${os.quoted_path(app.abs_path)}')
result :=
opt.verbose_execute('${os.quoted_path(v_exe)} ${flags} -d gg_record run ${os.quoted_path(app.abs_path)}')
if result.exit_code != 0 {
return error('Failed taking screenshot of `${app.abs_path}`:\n${result.output}')
}
@@ -400,7 +404,8 @@ fn take_screenshots(opt Options, app AppConfig) ![]string {
}
continue
}
extract_result := opt.verbose_execute('convert -extract ${region.width}x${region.height}+${region.x}+${region.y} "${out_file}" "${region_out_file}"')
extract_result :=
opt.verbose_execute('convert -extract ${region.width}x${region.height}+${region.x}+${region.y} "${out_file}" "${region_out_file}"')
if extract_result.exit_code != 0 {
p_app.signal_kill()
return error('Failed extracting region ${region_id} from screenshot of `${app.abs_path}` to "${region_out_file}":\n${result.output}')
@@ -482,8 +487,10 @@ fn new_config(root_path string, toml_config string) !Config {
// Merge, per app, overwrites
mut merged_compare := CompareOptions{}
merged_compare.method = app_any.value('compare.method').default_to(default_compare.method).string()
merged_compare_flags := app_any.value('compare.flags').default_to(empty_toml_array).array().as_strings()
merged_compare.method =
app_any.value('compare.method').default_to(default_compare.method).string()
merged_compare_flags :=
app_any.value('compare.flags').default_to(empty_toml_array).array().as_strings()
if merged_compare_flags.len > 0 {
merged_compare.flags = merged_compare_flags
} else {
@@ -491,15 +498,18 @@ fn new_config(root_path string, toml_config string) !Config {
}
mut merged_capture := CaptureOptions{}
merged_capture.method = app_any.value('capture.method').default_to(default_capture.method).string()
merged_capture_flags := app_any.value('capture.flags').default_to(empty_toml_array).array().as_strings()
merged_capture.method =
app_any.value('capture.method').default_to(default_capture.method).string()
merged_capture_flags :=
app_any.value('capture.flags').default_to(empty_toml_array).array().as_strings()
if merged_capture_flags.len > 0 {
merged_capture.flags = merged_capture_flags
} else {
merged_capture.flags = default_capture.flags
}
app_capture_regions_any := app_any.value('capture.regions').default_to(empty_toml_array).array()
app_capture_regions_any :=
app_any.value('capture.regions').default_to(empty_toml_array).array()
mut app_capture_regions := []CaptureRegion{}
for capture_region_any in app_capture_regions_any {
region := CaptureRegion{
@@ -523,7 +533,8 @@ fn new_config(root_path string, toml_config string) !Config {
}
merged_capture.regions = merged_capture_regions
merged_capture.wait_ms = app_any.value('capture.wait_ms').default_to(default_capture.wait_ms).int()
merged_capture.wait_ms =
app_any.value('capture.wait_ms').default_to(default_capture.wait_ms).int()
merge_capture_env := app_any.value('capture.env').default_to(empty_toml_map).as_map()
mut merge_env_map := default_capture.env.clone()
for k, v in merge_capture_env {
+9 -6
View File
@@ -61,8 +61,7 @@ const vls_manifest_path = os.join_path(vls_folder, 'vls.config.json')
const vls_src_folder = os.join_path(vls_folder, 'src')
const server_not_found_err = error_with_code('Language server is not installed nor found.',
101)
const server_not_found_err = error_with_code('Language server is not installed nor found.', 101)
fn (upd VlsUpdater) check_or_create_vls_folder() ! {
if !os.exists(vls_folder) {
@@ -240,13 +239,15 @@ fn (upd VlsUpdater) compile_from_source() ! {
if !os.exists(vls_src_folder) {
upd.log('Cloning VLS repo...')
clone_result := os.execute('${os.quoted_path(vexe)} retry -- ${git} clone --filter=blob:none https://github.com/vlang/vls ${vls_src_folder}')
clone_result :=
os.execute('${os.quoted_path(vexe)} retry -- ${git} clone --filter=blob:none https://github.com/vlang/vls ${vls_src_folder}')
if clone_result.exit_code != 0 {
return error('Failed to build VLS from source. Reason: ${clone_result.output}')
}
} else {
upd.log('Updating VLS repo...')
pull_result := os.execute('${os.quoted_path(vexe)} retry -- ${git} -C ${vls_src_folder} pull')
pull_result :=
os.execute('${os.quoted_path(vexe)} retry -- ${git} -C ${vls_src_folder} pull')
if !upd.is_force && pull_result.output.trim_space() == 'Already up to date.' {
upd.log('VLS was already updated to its latest version.')
return
@@ -308,7 +309,8 @@ fn (mut upd VlsUpdater) parse(mut fp flag.FlagParser) ! {
upd.output = .silent
}
is_install := fp.bool('install', ` `, false, 'Installs the language server. You may also use this flag to re-download or force update your existing installation.')
is_install := fp.bool('install', ` `, false,
'Installs the language server. You may also use this flag to re-download or force update your existing installation.')
is_update := fp.bool('update', ` `, false, 'Updates the installed language server.')
upd.is_check = fp.bool('check', ` `, false, 'Checks if the language server is installed.')
upd.is_force = fp.bool('force', ` `, false, 'Force install or update the language server.')
@@ -339,7 +341,8 @@ fn (mut upd VlsUpdater) parse(mut fp flag.FlagParser) ! {
}
}
upd.is_help = fp.bool('help', `h`, false, "Show this updater's help text. To show the help text for the language server, pass the `--ls` flag before it.")
upd.is_help = fp.bool('help', `h`, false,
"Show this updater's help text. To show the help text for the language server, pass the `--ls` flag before it.")
if !upd.is_help && !upd.pass_to_ls {
// automatically set the cli launcher to language server mode
+11 -7
View File
@@ -155,10 +155,12 @@ fn (opt &Options) diff_undocumented_functions_in_paths(path_old string, path_new
mut differs := []UndocumentedFN{}
if new_undocumented_functions.len > old_undocumented_functions.len {
for new_undoc_fn in new_undocumented_functions {
new_relative_file := new_undoc_fn.file.replace(new, '').trim_string_left(os.path_separator)
new_relative_file :=
new_undoc_fn.file.replace(new, '').trim_string_left(os.path_separator)
mut found := false
for old_undoc_fn in old_undocumented_functions {
old_relative_file := old_undoc_fn.file.replace(old, '').trim_string_left(os.path_separator)
old_relative_file :=
old_undoc_fn.file.replace(old, '').trim_string_left(os.path_separator)
if new_relative_file == old_relative_file
&& new_undoc_fn.signature == old_undoc_fn.signature {
found = true
@@ -229,15 +231,18 @@ fn main() {
// Collect tool options
mut opt := Options{
show_help: fp.bool('help', `h`, false, 'Show this help text.')
deprecated: fp.bool('deprecated', `d`, false, 'Include deprecated functions in output.')
deprecated: fp.bool('deprecated', `d`, false,
'Include deprecated functions in output.')
private: fp.bool('private', `p`, false, 'Include private functions in output.')
js: fp.bool('js', 0, false, 'Include JavaScript functions in output.')
no_line_numbers: fp.bool('no-line-numbers', `n`, false, 'Exclude line numbers in output.')
collect_tags: fp.bool('tags', `t`, false, 'Also print function tags if any is found.')
exclude: fp.string_multi('exclude', `e`, '')
relative_paths: fp.bool('relative-paths', `r`, false, 'Use relative paths in output.')
diff: fp.bool('diff', 0, false, 'exit(1) and show difference between two PATH inputs, return 0 otherwise.')
verify: fp.bool('verify', 0, false, 'exit(1) if documentation is missing, 0 otherwise.')
diff: fp.bool('diff', 0, false,
'exit(1) and show difference between two PATH inputs, return 0 otherwise.')
verify: fp.bool('verify', 0, false,
'exit(1) if documentation is missing, 0 otherwise.')
}
opt.additional_args = fp.finalize() or { panic(err) }
if opt.show_help {
@@ -283,8 +288,7 @@ fn main() {
for path in opt.additional_args {
if path in ['@vlib', '@cmd', '@examples'] {
rpath := path[1..]
total += opt.report_undocumented_functions_in_path(os.join_path(@VEXEROOT,
rpath))
total += opt.report_undocumented_functions_in_path(os.join_path(@VEXEROOT, rpath))
continue
}
if os.is_file(path) || os.is_dir(path) {
+6 -3
View File
@@ -83,7 +83,8 @@ fn get_mod_vpm_info_with_selector(name string, mut selector VpmInstallServerSele
is_initial_selection := selected_server_url(false, '') == ''
for url in selector.metadata_server_urls() {
modurl := url + '/api/packages/${name}'
verbose_println_more(@FILE_LINE, @FN, 'Retrieving metadata for `${name}` from `${modurl}` by making a GET request ...')
verbose_println_more(@FILE_LINE, @FN,
'Retrieving metadata for `${name}` from `${modurl}` by making a GET request ...')
r := http.get(modurl) or {
errors << 'Http server did not respond to our request for `${modurl}`.'
errors << 'Error details: ${err}'
@@ -179,7 +180,8 @@ fn get_ident_from_url(raw_url string) !(string, string) {
return error(final_error)
}
name = name.trim_string_right('.git')
verbose_println_more(@FILE_LINE, @FN, 'raw_url: ${raw_url}; publisher: ${publisher}; name: ${name}')
verbose_println_more(@FILE_LINE, @FN,
'raw_url: ${raw_url}; publisher: ${publisher}; name: ${name}')
return publisher, name
}
@@ -273,7 +275,8 @@ fn normalize_repo_lookup_url(raw_url string) !string {
return error('failed to parse module URL `${raw_url}`.')
}
host := url.hostname().trim_space().to_lower()
path := url.path.trim_space().trim_right('/').trim_left('/').trim_string_right('.git').to_lower()
path :=
url.path.trim_space().trim_right('/').trim_left('/').trim_string_right('.git').to_lower()
if host == '' || path == '' {
return error('failed to normalize module URL `${raw_url}`.')
}
+4 -4
View File
@@ -93,12 +93,12 @@ fn test_install_from_local_git_repository_variants() {
fn create_local_git_module(repo_path string, module_name string) {
os.mkdir_all(repo_path) or { panic(err) }
os.write_file(os.join_path(repo_path, 'v.mod'), "Module{\n\tname: '${module_name}'\n\tversion: '0.0.1'\n}\n") or {
panic(err)
}
os.write_file(os.join_path(repo_path, 'v.mod'),
"Module{\n\tname: '${module_name}'\n\tversion: '0.0.1'\n}\n") or { panic(err) }
cmd_ok(@LOCATION, 'git init ${os.quoted_path(repo_path)}')
cmd_ok(@LOCATION, 'git -C ${os.quoted_path(repo_path)} add v.mod')
cmd_ok(@LOCATION, 'git -C ${os.quoted_path(repo_path)} -c user.email="ci@vlang.io" -c user.name="V CI" commit -m "initial commit"')
cmd_ok(@LOCATION,
'git -C ${os.quoted_path(repo_path)} -c user.email="ci@vlang.io" -c user.name="V CI" commit -m "initial commit"')
}
fn file_url(path string) string {
+6 -6
View File
@@ -105,14 +105,12 @@ fn test_install_once() {
assert manifest.name == 'pcre'
assert manifest.description == 'A simple regex library for V.'
// Ensure the before installed markdown module wasn't modified.
assert md_last_modified == os.file_last_mod_unix(os.join_path(test_path, 'markdown',
'v.mod'))
assert md_last_modified == os.file_last_mod_unix(os.join_path(test_path, 'markdown', 'v.mod'))
// Try installing two modules that are both already installed.
res = cmd_ok(@LOCATION, install_cmd)
assert res.output.contains('All modules are already installed.'), res.output
assert md_last_modified == os.file_last_mod_unix(os.join_path(test_path, 'markdown',
'v.mod'))
assert md_last_modified == os.file_last_mod_unix(os.join_path(test_path, 'markdown', 'v.mod'))
}
fn test_missing_repo_name_in_url() {
@@ -161,7 +159,8 @@ fn test_get_installed_version() {
// Create a tag -> latests commit and tag are at the same state,
// but it should not be treated as a version installation, when there is another head branch.
res = cmd_ok(@LOCATION, 'git tag v0.1.0 -m "some tag message"') // note: without a tag message, git will try to start an editor when you run this test locally, which will block
res =
cmd_ok(@LOCATION, 'git tag v0.1.0 -m "some tag message"') // note: without a tag message, git will try to start an editor when you run this test locally, which will block
mod.is_installed = false
mod.get_installed()
assert mod.is_installed
@@ -195,7 +194,8 @@ fn test_install_from_hg_url() ! {
println('> writing .hg/hgrc to the new mercurial repo ...')
os.mkdir_all(os.join_path(test_module_path, '.hg'))!
os.write_file(os.join_path(test_module_path, '.hg/hgrc'), '[ui]\nusername = v_ci <v_ci@example.net>\nverbose = False\n')!
os.write_file(os.join_path(test_module_path, '.hg/hgrc'),
'[ui]\nusername = v_ci <v_ci@example.net>\nverbose = False\n')!
println('> writing .hg/hgrc done.')
mut p, mut port := test_utils.hg_serve(hg_path, test_module_path, 2000)
+4 -2
View File
@@ -53,14 +53,16 @@ fn test_reinstall_mod_with_version_installation() {
expect_args := [vexe, ident, tag, new_tag, install_path].join(' ')
// Decline.
decline_test := os.join_path(expect_tests_path, 'decline_reinstall_mod_with_version_installation.expect')
decline_test := os.join_path(expect_tests_path,
'decline_reinstall_mod_with_version_installation.expect')
manifest_path := os.join_path(install_path, 'v.mod')
last_modified := os.file_last_mod_unix(manifest_path)
cmd_ok(@LOCATION, '${expect_exe} ${decline_test} ${expect_args}')
assert last_modified == os.file_last_mod_unix(manifest_path)
// Accept.
accept_test := os.join_path(expect_tests_path, 'accept_reinstall_mod_with_version_installation.expect')
accept_test := os.join_path(expect_tests_path,
'accept_reinstall_mod_with_version_installation.expect')
cmd_ok(@LOCATION, '${expect_exe} ${accept_test} ${expect_args}')
manifest = get_vmod(ident)
assert manifest.name == ident
+10 -5
View File
@@ -152,7 +152,8 @@ const solve_flags = [
]
fn run_confirm(cmd cli.Command) ! {
run_issue(cmd, confirm_search_query, 'still unconfirmed', 'Help us by confirming and triaging this issue:')!
run_issue(cmd, confirm_search_query, 'still unconfirmed',
'Help us by confirming and triaging this issue:')!
}
fn run_fix(cmd cli.Command) ! {
@@ -160,7 +161,8 @@ fn run_fix(cmd cli.Command) ! {
}
fn run_implement(cmd cli.Command) ! {
run_issue(cmd, feature_search_query, 'feature request', 'Help us by implementing the issue in a PR, or triage it:')!
run_issue(cmd, feature_search_query, 'feature request',
'Help us by implementing the issue in a PR, or triage it:')!
}
fn run_solve(cmd cli.Command) ! {
@@ -188,7 +190,8 @@ fn run_solve(cmd cli.Command) ! {
}
start_page, end_page := resolve_page_range(cmd, max_pages)!
page := start_page + (rand.intn(end_page - start_page + 1) or { 0 })
eprintln(term.colorize(term.gray, 'Found: ${total} bugs reproducible on ${os_label}. Fetching from page: ${page} in [${start_page}, ${end_page}] ...'))
eprintln(term.colorize(term.gray,
'Found: ${total} bugs reproducible on ${os_label}. Fetching from page: ${page} in [${start_page}, ${end_page}] ...'))
issue := fetch_issue_from_page(query, page)!
details := fetch_issue_details(issue.number)!
@@ -273,7 +276,8 @@ fn run_issue(cmd cli.Command, issue_query string, issue_label string, help_label
}
start_page, end_page := resolve_page_range(cmd, max_pages)!
page := start_page + (rand.intn(end_page - start_page + 1) or { 0 })
eprintln(term.colorize(term.gray, 'Found: ${total} ${issue_label} issues. Fetching issue from page: ${page} in [${start_page}, ${end_page}] ...'))
eprintln(term.colorize(term.gray,
'Found: ${total} ${issue_label} issues. Fetching issue from page: ${page} in [${start_page}, ${end_page}] ...'))
issue := fetch_issue_from_page(issue_query, page)!
println(term.colorize(term.green, help_label))
println(issue.html_url)
@@ -284,7 +288,8 @@ fn run_issue(cmd cli.Command, issue_query string, issue_label string, help_label
}
fn run_document(_cmd cli.Command) ! {
res := os.execute('${os.quoted_path(@VEXE)} missdoc --exclude vlib/v --exclude /linux_bare/ --exclude /wasm_bare/ @vlib')
res :=
os.execute('${os.quoted_path(@VEXE)} missdoc --exclude vlib/v --exclude /linux_bare/ --exclude /wasm_bare/ @vlib')
if res.exit_code != 0 {
return error('v missdoc failed: ${res.output}')
}
+10 -11
View File
@@ -19,9 +19,12 @@ fn main() {
fp.description('This tool will reduce the code file and try to make the smallest one it can that reproduces the error when the command is executed')
fp.version(version)
error_msg := fp.string('error_msg', `m`, default_error_msg, 'the error message you want to reproduce, default: \'${default_error_msg}\'')
mut command := fp.string('command', `c`, default_command, 'the command used to try to reproduce the error, default: \'${default_command}\', will replace PATH with the path of the folder where it is run')
copy_project := fp.bool('cp', `p`, false, 'if used v reduce will copy the whole folder of the project')
error_msg := fp.string('error_msg', `m`, default_error_msg,
'the error message you want to reproduce, default: \'${default_error_msg}\'')
mut command := fp.string('command', `c`, default_command,
'the command used to try to reproduce the error, default: \'${default_command}\', will replace PATH with the path of the folder where it is run')
copy_project := fp.bool('cp', `p`, false,
'if used v reduce will copy the whole folder of the project')
timeout := fp.int('to', `t`, 0, 'sets a timeout for the command, default=0 : no timeout')
do_fmt := fp.bool('fmt', `w`, false, 'enable v fmt for the output (rpdc_file_name.v)')
file_paths := fp.finalize() or {
@@ -80,8 +83,8 @@ fn main() {
// start tests
tmp_code := create_code(parse(content))
warn_on_false(string_reproduces(tmp_code, error_msg, command, full_file_path, true,
timeout), 'string_reproduces', @LOCATION)
warn_on_false(string_reproduces(tmp_code, error_msg, command, full_file_path, true, timeout),
'string_reproduces', @LOCATION)
show_code_stats(tmp_code, label: 'Code size without comments')
// reduce the code
@@ -334,9 +337,7 @@ fn reduce_scope(content string, error_msg string, command string, do_fmt bool, f
item.tmp_ignored = true // try to ignore it
code := create_code(sc)
item.tmp_ignored = false // dont need it anymore
if string_reproduces(code, error_msg, command, file_path, false,
timeout)
{
if string_reproduces(code, error_msg, command, file_path, false, timeout) {
item.ignored = true
modified_smth = true
outer_modified_smth = true
@@ -411,9 +412,7 @@ fn reduce_scope(content string, error_msg string, command string, do_fmt bool, f
item.tmp_ignored = true
code := create_code(line_tree)
item.tmp_ignored = false // dont need it anymore
if string_reproduces(code, error_msg, command, file_path, false,
timeout)
{
if string_reproduces(code, error_msg, command, file_path, false, timeout) {
item.ignored = true
modified_smth = true
outer_modified_smth = true
+28 -14
View File
@@ -424,24 +424,38 @@ fn (mut context Context) parse_options() ! {
fp.limit_free_args_to_at_least(1)!
context.show_help = fp.bool('help', `h`, false, 'Show this help screen.')
context.run_count = fp.int('runs', `r`, 10, 'Run count. Default: 10')
context.repeats_count = fp.int('repeats', `R`, 1, 'Repeats count (it repeats everything, including reporting). Default: 1')
context.warmup = fp.int('warmup', `w`, 2, 'Warmup run count. These are done *at the start* of each series, and the timings are ignored. Default: 2')
context.series = fp.int('series', `s`, 1, 'Series count. `-s 2 -r 4 a b` => aaaabbbbaaaabbbb, while `-s 3 -r 2 a b` => aabbaabbaabb. Default: 1')
context.ignore_failed = fp.bool('ignore', `e`, false, 'Ignore failed commands (returning a non 0 exit code).')
context.no_vexe_setenv = fp.bool('no_vexe_reset', `N`, false, 'Do not reset the VEXE env variable at the start. \n By default, VEXE will be set to "", to allow for measuring different V executables. Use this option to override it')
context.use_newline = fp.bool('newline', `n`, false, 'Use \\n, do not overwrite the last line. Produces more output, but easier to diagnose.')
context.is_silent = fp.bool('silent', `S`, false, 'Do not show progress lines, print only the final summary. Suitable for CIs.')
context.repeats_count = fp.int('repeats', `R`, 1,
'Repeats count (it repeats everything, including reporting). Default: 1')
context.warmup = fp.int('warmup', `w`, 2,
'Warmup run count. These are done *at the start* of each series, and the timings are ignored. Default: 2')
context.series = fp.int('series', `s`, 1,
'Series count. `-s 2 -r 4 a b` => aaaabbbbaaaabbbb, while `-s 3 -r 2 a b` => aabbaabbaabb. Default: 1')
context.ignore_failed = fp.bool('ignore', `e`, false,
'Ignore failed commands (returning a non 0 exit code).')
context.no_vexe_setenv = fp.bool('no_vexe_reset', `N`, false,
'Do not reset the VEXE env variable at the start. \n By default, VEXE will be set to "", to allow for measuring different V executables. Use this option to override it')
context.use_newline = fp.bool('newline', `n`, false,
'Use \\n, do not overwrite the last line. Produces more output, but easier to diagnose.')
context.is_silent = fp.bool('silent', `S`, false,
'Do not show progress lines, print only the final summary. Suitable for CIs.')
if os.getenv('VREPEAT_SILENT') != '' {
context.is_silent = true
}
context.show_output = fp.bool('output', `O`, false, 'Show command stdout/stderr in the progress indicator for each command. Note: slower, for verbose commands.')
context.show_output = fp.bool('output', `O`, false,
'Show command stdout/stderr in the progress indicator for each command. Note: slower, for verbose commands.')
context.verbose = fp.bool('verbose', `v`, false, 'Be more verbose.')
context.fail_on_maxtime = fp.int('max_time', `m`, max_time, 'Fail with exit code 2, when first cmd takes above M milliseconds (regression). Default: ${max_time}')
context.fail_on_regress_percent = fp.int('fail_percent', `f`, max_fail_percent, 'Fail with exit code 3, when first cmd is X% slower than the rest (regression). Default: ${max_fail_percent}')
context.cmd_template = fp.string('template', `t`, '{T}', 'Command template. {T} will be substituted with the current command. Default: {T}. \n Here is an example, that will produce and run 24 permutations = (3 for opt) x (2 for source) x (4 = v names):\n v repeat -p opt=-check-syntax,-check,"-o x.c" -p source=examples/hello_world.v,examples/hanoi.v --template "./{T} {opt} {source}" vold vnew vold_prod vnew_prod')
cmd_params := fp.string_multi('parameter', `p`, 'A parameter substitution list. `pp=val1,val2,val2` means that {pp} in the template, will be substituted with *each* of val1, val2, val3.')
context.nmins = fp.int('nmins', `i`, 0, 'Ignore the BOTTOM X results (minimum execution time). Makes the results more robust to performance flukes. Default: 0')
context.nmaxs = fp.int('nmaxs', `a`, 0, 'Ignore the TOP X results (maximum execution time). Makes the results more robust to performance flukes. Default: 0')
context.fail_on_maxtime = fp.int('max_time', `m`, max_time,
'Fail with exit code 2, when first cmd takes above M milliseconds (regression). Default: ${max_time}')
context.fail_on_regress_percent = fp.int('fail_percent', `f`, max_fail_percent,
'Fail with exit code 3, when first cmd is X% slower than the rest (regression). Default: ${max_fail_percent}')
context.cmd_template = fp.string('template', `t`, '{T}',
'Command template. {T} will be substituted with the current command. Default: {T}. \n Here is an example, that will produce and run 24 permutations = (3 for opt) x (2 for source) x (4 = v names):\n v repeat -p opt=-check-syntax,-check,"-o x.c" -p source=examples/hello_world.v,examples/hanoi.v --template "./{T} {opt} {source}" vold vnew vold_prod vnew_prod')
cmd_params := fp.string_multi('parameter', `p`,
'A parameter substitution list. `pp=val1,val2,val2` means that {pp} in the template, will be substituted with *each* of val1, val2, val3.')
context.nmins = fp.int('nmins', `i`, 0,
'Ignore the BOTTOM X results (minimum execution time). Makes the results more robust to performance flukes. Default: 0')
context.nmaxs = fp.int('nmaxs', `a`, 0,
'Ignore the TOP X results (maximum execution time). Makes the results more robust to performance flukes. Default: 0')
for p in cmd_params {
parts := p.split('=')
if parts.len > 1 {
+6 -4
View File
@@ -306,7 +306,8 @@ fn (r &Repl) check_fn_type_kind(new_line string) FnType {
// -usecache keeps repeated REPL checks responsive by reusing cached modules.
// -w suppresses warnings from this synthetic println probe.
// -check just does syntax and checker analysis without generating/running code.
os_response := os.execute('${os.quoted_path(vexe)} -usecache -w -check ${os.quoted_path(check_file)}')
os_response :=
os.execute('${os.quoted_path(vexe)} -usecache -w -check ${os.quoted_path(check_file)}')
str_response := convert_output(os_response.output)
if os_response.exit_code != 0 && str_response.contains('can not print void expressions') {
return FnType.void
@@ -612,8 +613,8 @@ fn run_repl(workdir string, vrepl_prefix string) int {
}
} else {
func_call, fntype := r.function_call(r.line)
filter_line := r.line.replace(r.line.find_between("'", "'"), '').replace(r.line.find_between('"',
'"'), '')
filter_line :=
r.line.replace(r.line.find_between("'", "'"), '').replace(r.line.find_between('"', '"'), '')
mut is_statement := false
if filter_line.count('=') % 2 == 1
&& (filter_line.count('!=') + filter_line.count('>=') + filter_line.count('<=')) == 0 {
@@ -855,7 +856,8 @@ fn repl_check_vfile(file string) !os.Result {
}
// Declaration-only REPL lines do not need code generation or execution.
// Cached checks keep repeated imports and definitions responsive.
s := os.execute('${os.quoted_path(vexe)} -usecache -message-limit 1 -repl -check ${os.quoted_path(file)}')
s :=
os.execute('${os.quoted_path(vexe)} -usecache -message-limit 1 -repl -check ${os.quoted_path(file)}')
if s.exit_code < 0 {
rerror(s.output)
return error(s.output)
+4 -2
View File
@@ -22,8 +22,10 @@ fn main() {
fp.skip_executable()
fp.limit_free_args_to_at_least(1)!
context.show_help = fp.bool('help', `h`, false, 'Show this help screen.')
context.timeout = fp.float('timeout', `t`, 900.0, 'Timeout in seconds (for all retries). Default: 900.0 seconds (15 minutes).') * time.second
context.delay = fp.float('delay', `d`, 1.0, 'Delay between each retry in seconds. Default: 1.0 second.') * time.second
context.timeout = fp.float('timeout', `t`, 900.0,
'Timeout in seconds (for all retries). Default: 900.0 seconds (15 minutes).') * time.second
context.delay = fp.float('delay', `d`, 1.0,
'Delay between each retry in seconds. Default: 1.0 second.') * time.second
context.retries = fp.int('retries', `r`, 10, 'Maximum number of retries. Default: 10.')
if context.show_help {
println(fp.usage())
+4 -2
View File
@@ -58,8 +58,10 @@ fn run_parent_mode() {
fp.description('Probe net.http HTTPS POST behavior around 16KB payloads using https://httpbin.org/post.')
fp.skip_executable()
expect_mode := fp.string('expect', `e`, 'after', 'Expected behavior mode: before|after|none. before expects >16KB failures, after expects all succeed.')
sizes_csv := fp.string('sizes', `s`, default_sizes_csv, 'Comma separated payload sizes in bytes.')
expect_mode := fp.string('expect', `e`, 'after',
'Expected behavior mode: before|after|none. before expects >16KB failures, after expects all succeed.')
sizes_csv := fp.string('sizes', `s`, default_sizes_csv,
'Comma separated payload sizes in bytes.')
verbose := fp.bool('verbose', `v`, false, 'Print child process output for all sizes.')
show_help := fp.bool('help', `h`, false, 'Show this help screen.')
free_args := fp.finalize() or {
+2 -1
View File
@@ -23,7 +23,8 @@ fn main() {
vexe_name := os.file_name(vexe)
short_v_name := vexe_name.all_before('.')
recompilation.must_be_enabled(vroot, 'Please install V from source, to use `${vexe_name} self` .')
recompilation.must_be_enabled(vroot,
'Please install V from source, to use `${vexe_name} self` .')
os.chdir(vroot)!
os.setenv('VCOLORS', 'always', true)
repeat_count, mut args := extract_repeat_count(args_[1..].filter(it != 'self'))
+2 -1
View File
@@ -15,7 +15,8 @@ fn main() {
if os.is_dir(freetype_folder) {
println('Thirdparty "freetype" is already installed.')
} else {
s := os.execute('${os.quoted_path(vexe)} retry -- git clone --filter=blob:none ${freetype_repo_url} ${freetype_folder}')
s :=
os.execute('${os.quoted_path(vexe)} retry -- git clone --filter=blob:none ${freetype_repo_url} ${freetype_folder}')
if s.exit_code != 0 {
panic(s.output)
}
+3 -3
View File
@@ -87,7 +87,8 @@ fn main() {
show_help: fp.bool('help', `h`, false, 'Show this help text.')
force_update: fp.bool('force-update', `u`, false, 'Force update of the sokol-shdc tool.')
verbose: fp.bool('verbose', `v`, false, 'Be verbose about the tools progress.')
slangs: fp.string_multi('slang', `l`, 'Shader dialects to generate code for. Default is all.\n Available dialects: ${supported_slangs}')
slangs: fp.string_multi('slang', `l`,
'Shader dialects to generate code for. Default is all.\n Available dialects: ${supported_slangs}')
}
if opt.show_help {
println(fp.usage())
@@ -247,8 +248,7 @@ fn ensure_external_tools(opt Options) ! {
if is_shdc_available {
eprintln(' file path: ${shdc_exe}')
eprintln(' file size: ${os.file_size(shdc_exe)}')
eprintln(' file time: ${time.unix_microsecond(os.file_last_mod_unix(shdc_exe),
0)}')
eprintln(' file time: ${time.unix_microsecond(os.file_last_mod_unix(shdc_exe), 0)}')
}
}
if is_shdc_available && is_shdc_executable {
+4 -2
View File
@@ -330,7 +330,8 @@ fn (mut app App) exec_file(path string) {
trimmed := stmt.trim_space()
// Strip comment-only lines to decide if the chunk has real SQL,
// but pass the original (with comments) to SQLite so it can parse them.
sql_content := trimmed.split('\n').filter(!it.trim_space().starts_with('--')).join('\n').trim_space()
sql_content :=
trimmed.split('\n').filter(!it.trim_space().starts_with('--')).join('\n').trim_space()
if sql_content == '' {
continue
}
@@ -348,7 +349,8 @@ fn (mut app App) read_file_repl(path string) {
mut count := 0
for stmt in split_statements(content) {
trimmed := stmt.trim_space()
sql_content := trimmed.split('\n').filter(!it.trim_space().starts_with('--')).join('\n').trim_space()
sql_content :=
trimmed.split('\n').filter(!it.trim_space().starts_with('--')).join('\n').trim_space()
if sql_content == '' {
continue
}
+2 -2
View File
@@ -150,8 +150,8 @@ fn set_reg_value(reg_key voidptr, key string, value string) !bool {
// letting them know that the system environment has changed and should be reloaded
fn send_setting_change_msg(message_data string) !bool {
message_data_wide := message_data.to_wide()
if C.SendMessageTimeoutW(os.hwnd_broadcast, os.wm_settingchange, 0, unsafe { &u32(message_data_wide) },
os.smto_abortifhung, 5000, 0) == 0 {
if C.SendMessageTimeoutW(os.hwnd_broadcast, os.wm_settingchange, 0,
unsafe { &u32(message_data_wide) }, os.smto_abortifhung, 5000, 0) == 0 {
return error('Could not broadcast WM_SETTINGCHANGE')
}
return true
+6 -4
View File
@@ -43,7 +43,9 @@ const vfmt_verify_list = [
'vlib/',
]
const vfmt_known_failing_exceptions = arrays.merge(verify_known_failing_exceptions, []string{})
const vfmt_known_failing_exceptions = arrays.merge(verify_known_failing_exceptions, [
'vlib/v/tests/structs/anon_struct_local_init_test.v',
])
const vexe = os.getenv('VEXE')
@@ -88,10 +90,10 @@ fn v_test_vetting(vargs string) ! {
'${os.quoted_path(vexe)} fmt -inprocess -verify', 'fmt -inprocess -verify'
}
vfmt_list := util.find_all_v_files(vfmt_verify_list) or { return }
exceptions := (util.find_all_v_files(vfmt_known_failing_exceptions) or { return }).map(os.abs_path)
exceptions :=
(util.find_all_v_files(vfmt_known_failing_exceptions) or { return }).map(os.abs_path)
filtered_vfmt_list := vfmt_list.filter(os.abs_path(it) !in exceptions)
verify_session := tsession(vargs, 'vfmt.v', fmt_cmd, fmt_args, filtered_vfmt_list,
exceptions)
verify_session := tsession(vargs, 'vfmt.v', fmt_cmd, fmt_args, filtered_vfmt_list, exceptions)
if vet_session.benchmark.nfail > 0 || verify_session.benchmark.nfail > 0 {
eprintln('\n')
+12 -6
View File
@@ -106,12 +106,18 @@ fn process_cli_args() &Context {
context.is_verbose = fp.bool('verbose', `v`, false, 'Be more verbose.')
context.is_silent = fp.bool('silent', `S`, false, 'Do not print progress at all.')
context.is_linear = fp.bool('linear', `L`, false, 'Print linear progress log. Suitable for CI.')
context.show_src = fp.bool('show_source', `E`, false, 'Print the partial source code that caused a fault/panic in the parser.')
context.period_ms = fp.int('progress_ms', `s`, 500, 'print a status report periodically, the period is given in milliseconds.')
context.is_worker = fp.bool('worker', `w`, false, 'worker specific flag - is this a worker process, that can crash/panic.')
context.cut_index = fp.int('cut_index', `c`, 1, 'worker specific flag - cut index in the source file, everything before that will be parsed, the rest - ignored.')
context.timeout_ms = fp.int('timeout_ms', `t`, 250, 'worker specific flag - timeout in ms; a worker taking longer, will self terminate.')
context.path = fp.string('path', `p`, '', 'worker specific flag - path to the current source file, which will be parsed.')
context.show_src = fp.bool('show_source', `E`, false,
'Print the partial source code that caused a fault/panic in the parser.')
context.period_ms = fp.int('progress_ms', `s`, 500,
'print a status report periodically, the period is given in milliseconds.')
context.is_worker = fp.bool('worker', `w`, false,
'worker specific flag - is this a worker process, that can crash/panic.')
context.cut_index = fp.int('cut_index', `c`, 1,
'worker specific flag - cut index in the source file, everything before that will be parsed, the rest - ignored.')
context.timeout_ms = fp.int('timeout_ms', `t`, 250,
'worker specific flag - timeout in ms; a worker taking longer, will self terminate.')
context.path = fp.string('path', `p`, '',
'worker specific flag - path to the current source file, which will be parsed.')
if context.is_help {
println(fp.usage())
+3 -3
View File
@@ -40,8 +40,7 @@ fn main() {
for targ in args_after {
if os.is_dir(targ) {
// Fetch all tests from the directory
files, skip_files := ctx.should_test_dir(targ.trim_right(os.path_separator),
backend)
files, skip_files := ctx.should_test_dir(targ.trim_right(os.path_separator), backend)
ts.files << files
ts.skip_files << skip_files
continue
@@ -200,7 +199,8 @@ fn (mut ctx Context) should_test_when_it_contains_matching_fns(path string, _bac
fn extract_flag_bool(flag_name string, mut after []string, flag_default bool) bool {
mut res := flag_default
orig_after := after.clone() // workaround for after.filter() codegen bug, when `mut after []string`
orig_after :=
after.clone() // workaround for after.filter() codegen bug, when `mut after []string`
matches_after := orig_after.filter(it != flag_name)
if matches_after.len < after.len {
after = matches_after.clone()
+2 -1
View File
@@ -56,7 +56,8 @@ fn test_with_several_test_files() {
fn test_with_stats_and_several_test_files() {
// There should be more OKs here, since the output will have the inner OKs for each individual test fn:
res := os.execute_or_exit('${os.quoted_path(mytest_exe)} -stats test ${os.quoted_path(tpath_passing)}')
res :=
os.execute_or_exit('${os.quoted_path(mytest_exe)} -stats test ${os.quoted_path(tpath_passing)}')
assert res.output.contains('1 assert'), res.output
assert res.output.contains('3 asserts'), res.output
assert res.output.contains('2 passed, 2 total'), res.output
+2 -1
View File
@@ -232,7 +232,8 @@ fn (app App) install_git() {
}
println('Downloading git 32 bit for Windows, please wait.')
// We'll use 32 bit because maybe someone out there is using 32-bit windows
res_download := os.execute('bitsadmin.exe /transfer "vgit" https://github.com/git-for-windows/git/releases/download/v2.30.0.windows.2/Git-2.30.0.2-32-bit.exe "${os.getwd()}/git32.exe"')
res_download :=
os.execute('bitsadmin.exe /transfer "vgit" https://github.com/git-for-windows/git/releases/download/v2.30.0.windows.2/Git-2.30.0.2-32-bit.exe "${os.getwd()}/git32.exe"')
if res_download.exit_code != 0 {
eprintln('Unable to install git automatically: please install git manually')
panic(res_download.output)
+11 -8
View File
@@ -42,8 +42,8 @@ fn (mut vt VetAnalyze) stmt(vet &Vet, stmt ast.Stmt) {
ast.AssignStmt {
if stmt.op == .plus_assign {
if stmt.right[0] in [ast.StringLiteral, ast.StringInterLiteral] {
vt.save_expr(stringconcat_cutoff, '${stmt.left[0].str()} += ${stmt.right[0].str()}',
vet.file, stmt.pos)
vt.save_expr(stringconcat_cutoff,
'${stmt.left[0].str()} += ${stmt.right[0].str()}', vet.file, stmt.pos)
}
}
}
@@ -102,14 +102,15 @@ fn (mut vt VetAnalyze) expr(vet &Vet, expr ast.Expr) {
vt.call_counter['${int(vt.cur_fn.receiver.typ)}.${expr.name}']++
}
}
vt.save_expr(callexpr_cutoff, '${left_str}.${expr.name}(${expr.args.map(it.str()).join(', ')})',
vet.file, expr.pos)
vt.save_expr(callexpr_cutoff,
'${left_str}.${expr.name}(${expr.args.map(it.str()).join(', ')})', vet.file,
expr.pos)
} else {
lock vt.call_counter {
vt.call_counter[expr.name]++
}
vt.save_expr(callexpr_cutoff, '${expr.name}(${expr.args.map(it.str()).join(', ')})',
vet.file, expr.pos)
vt.save_expr(callexpr_cutoff,
'${expr.name}(${expr.args.map(it.str()).join(', ')})', vet.file, expr.pos)
}
}
ast.AsCast {
@@ -162,7 +163,8 @@ fn (mut vt VetAnalyze) vet_repeated_code(mut vet Vet) {
}
for file, info_pos in info {
for k, pos in info_pos {
vet.notice_with_file(file, '${expr} occurs ${k + 1}/${occurrences} times in ${scope_name}.',
vet.notice_with_file(file,
'${expr} occurs ${k + 1}/${occurrences} times in ${scope_name}.',
pos.line_nr, .repeated_code)
}
}
@@ -179,7 +181,8 @@ fn (mut vt VetAnalyze) vet_inlining_fn(mut vet Vet) {
if calls < fns_call_cutoff {
continue
}
vet.notice_with_file(file, '${fn_name.all_after('.')} fn might be inlined (possibly called at least ${calls} times)',
vet.notice_with_file(file,
'${fn_name.all_after('.')} fn might be inlined (possibly called at least ${calls} times)',
pos.line_nr, .inline_fn)
}
}
+2 -1
View File
@@ -43,7 +43,8 @@ fn check_path(vexe string, dir string, tests []string) int {
program := path
print(path + ' ')
file_options := get_file_options(path)
res := os.execute('${os.quoted_path(vexe)} vet -nocolor ${file_options.vflags} ${os.quoted_path(program)}')
res :=
os.execute('${os.quoted_path(vexe)} vet -nocolor ${file_options.vflags} ${os.quoted_path(program)}')
if res.exit_code < 0 {
panic(res.output)
}
+4 -4
View File
@@ -226,8 +226,8 @@ fn (mut vt Vet) vet_fn_documentation(lines []string, line string, lnumber int) {
}
if grab {
clean_line := line.all_before_last('{').trim(' ')
vt.warn('Function documentation seems to be missing for "${clean_line}".',
lnumber, .doc)
vt.warn('Function documentation seems to be missing for "${clean_line}".', lnumber,
.doc)
}
} else {
fn_name := ident_fn_name(line)
@@ -247,8 +247,8 @@ fn (mut vt Vet) vet_fn_documentation(lines []string, line string, lnumber int) {
&& !prev_prev_line.starts_with('//') {
grab = false
clean_line := line.all_before_last('{').trim(' ')
vt.warn('The documentation for "${clean_line}" seems incomplete.',
lnumber, .doc)
vt.warn('The documentation for "${clean_line}" seems incomplete.', lnumber,
.doc)
break
}
+1 -3
View File
@@ -63,7 +63,6 @@ const external_tools = [
'watch',
'where',
]
const list_of_flags_that_allow_duplicates = ['cc', 'd', 'define', 'cf', 'cflags']
const delegated_v2_exe_env = 'V_V2_EXE'
@[unsafe]
@@ -115,8 +114,7 @@ fn main() {
return
}
mut args_and_flags := util.join_env_vflags_and_os_args()[1..]
prefs, command := pref.parse_args_and_show_errors(external_tools, args_and_flags,
true)
prefs, command := pref.parse_args_and_show_errors(external_tools, args_and_flags, true)
maybe_delegate_to_vvmrc(command, prefs)
maybe_delegate_to_v2(command, prefs)
if prefs.use_cache && os.user_os() == 'windows' {
+6 -5
View File
@@ -50,7 +50,8 @@ fn test_vvmrc_delegates_to_matching_compiler_executable() {
bin_dir := os.join_path(tmp_root, 'bin')
os.mkdir_all(bin_dir) or { panic(err) }
fake_compiler_source := os.join_path(tmp_root, 'fake_compiler.v')
os.write_file(fake_compiler_source, "import os\nfn main() {\n\tprintln('${delegated_marker} ' + os.args[1..].join(' '))\n}\n") or {
os.write_file(fake_compiler_source,
"import os\nfn main() {\n\tprintln('${delegated_marker} ' + os.args[1..].join(' '))\n}\n") or {
panic(err)
}
fake_compiler_exe := os.join_path(bin_dir, if os.user_os() == 'windows' {
@@ -58,14 +59,14 @@ fn test_vvmrc_delegates_to_matching_compiler_executable() {
} else {
'v${requested_vvm_test_version}'
})
compile_res := os.execute('${os.quoted_path(current_vexe)} -o ${os.quoted_path(fake_compiler_exe)} ${os.quoted_path(fake_compiler_source)}')
compile_res :=
os.execute('${os.quoted_path(current_vexe)} -o ${os.quoted_path(fake_compiler_exe)} ${os.quoted_path(fake_compiler_source)}')
assert compile_res.exit_code == 0, compile_res.output
project_dir := os.join_path(tmp_root, 'project')
os.mkdir_all(project_dir) or { panic(err) }
os.write_file(os.join_path(project_dir, '.vvmrc'), requested_vvm_test_version) or { panic(err) }
os.write_file(os.join_path(project_dir, 'main.v'), "fn main() {\n\tprintln('from project')\n}\n") or {
panic(err)
}
os.write_file(os.join_path(project_dir, 'main.v'),
"fn main() {\n\tprintln('from project')\n}\n") or { panic(err) }
mut envs := os.environ()
path_key := find_path_env_key(envs)
envs[path_key] = '${bin_dir}${os.path_delimiter}${envs[path_key]}'
+3 -1
View File
@@ -189,6 +189,7 @@ fn draw_timeline(mut app App) {
cursor_x := margin + f32(app.selected_frame) * tick_spacing
// Triangle cursor
draw_triangle_filled(ctx, cursor_x, timeline_y + 15, cursor_x - 8, timeline_y + 5,
cursor_x + 8, timeline_y + 5, timeline_cursor)
// Vertical line
@@ -296,7 +297,8 @@ fn draw_details(mut app App) {
}
} else {
// Instructions
ctx.draw_text(20, int(details_y) + 20, 'Click on a histogram bar to select a frame, or use keyboard arrows to navigate',
ctx.draw_text(20, int(details_y) + 20,
'Click on a histogram bar to select a frame, or use keyboard arrows to navigate',
color: text_color
size: 16
)
+1 -2
View File
@@ -154,8 +154,7 @@ fn main() {
}
// Strip terminal control characters that script command may prepend
mut cleaned := gen_out.replace('\r\n', '\n').replace('\x04', '').replace('\x08',
'')
mut cleaned := gen_out.replace('\r\n', '\n').replace('\x04', '').replace('\x08', '')
// Remove "^D" literal string that macOS script may add
if cleaned.starts_with('^D') {
cleaned = cleaned[2..]
+2 -1
View File
@@ -14,7 +14,8 @@ fn main() {
fp.skip_executable()
fp.application('Sample generator for 1 billion rows challenge')
fp.description('The 1 billion rows challenge solved in V.\nFor details, see https://www.morling.dev/blog/one-billion-row-challenge/')
input_file := fp.string('city-file', `i`, 'cities.txt', 'Path to input file with cities and means list')
input_file := fp.string('city-file', `i`, 'cities.txt',
'Path to input file with cities and means list')
fp.limit_free_args_to_exactly(1)!
sample_count := fp.remaining_parameters()[0].u64()
+4 -2
View File
@@ -178,8 +178,10 @@ fn main() {
fp.application('1 billion rows challenge')
fp.description('The 1 billion rows challenge solved in V.\nFor details, see https://www.morling.dev/blog/one-billion-row-challenge/')
thread_count := u32(fp.int('threads', `n`, 1, 'number of threads for parallel processing.'))
print_nicely := fp.bool('human-readable', `h`, false, 'Print results with new lines rather than following challenge spec')
quiet := fp.bool('quiet', `q`, false, 'Suppress the results output (e.g., if you only care about timing)')
print_nicely := fp.bool('human-readable', `h`, false,
'Print results with new lines rather than following challenge spec')
quiet := fp.bool('quiet', `q`, false,
'Suppress the results output (e.g., if you only care about timing)')
fp.limit_free_args_to_exactly(1)!
path := fp.remaining_parameters()[0]
+6 -23
View File
@@ -503,26 +503,6 @@ fn ai_empty_count(board AiBoard) int {
return empty_tiles
}
@[inline]
fn ai_has_moves(board AiBoard) bool {
if ai_empty_count(board) > 0 {
return true
}
for y in 0 .. 4 {
for x in 0 .. 4 {
idx := y << 2 + x
value := ai_tile(board, idx)
if x < 3 && value == ai_tile(board, idx + 1) {
return true
}
if y < 3 && value == ai_tile(board, idx + 4) {
return true
}
}
}
return false
}
fn (ai &AiEngine) move_left(board AiBoard) (AiBoard, bool) {
mut res := AiBoard(0)
mut changed := false
@@ -1144,7 +1124,8 @@ fn (app &App) draw_tiles() {
th := tw // square tiles, w == h
xoffset := xstart + app.ui.padding_size + x * toffset
yoffset := ystart + app.ui.padding_size + y * toffset
app.gg.draw_rounded_rect_filled(xoffset, yoffset, tw, th, tw / 8, app.theme.tile_colors[0])
app.gg.draw_rounded_rect_filled(xoffset, yoffset, tw, th, tw / 8,
app.theme.tile_colors[0])
}
}
@@ -1184,10 +1165,12 @@ fn (app &App) draw_one_tile(x int, y int, tidx int) {
if oidx != 0xFFFF_FFFF {
scaling := app.ui.tile_size * easing.in_out_quint(app.mtickers[y][x])
if ox != x {
dx = math.clip(int(scaling * (f64(ox) - f64(x))), -4 * app.ui.tile_size, 4 * app.ui.tile_size)
dx = math.clip(int(scaling * (f64(ox) - f64(x))), -4 * app.ui.tile_size,
4 * app.ui.tile_size)
}
if oy != y {
dy = math.clip(int(scaling * (f64(oy) - f64(y))), -4 * app.ui.tile_size, 4 * app.ui.tile_size)
dy = math.clip(int(scaling * (f64(oy) - f64(y))), -4 * app.ui.tile_size,
4 * app.ui.tile_size)
}
}
tile_color := if tidx < app.theme.tile_colors.len {
+10 -11
View File
@@ -30,11 +30,16 @@ fn new_context() !&Context {
fp.description('Reads into memory selected sections of *.tar.gz. archives from https or home_dir.')
fp.skip_executable()
ctx := &Context{
url: fp.string('url', `u`, default_url, 'archive *.tar.gz URL, default(${default_url}). Start name with file:/// for local')
chunks: fp.bool('chunks', `c`, false, 'decompress with chunks to reduce RAM usage, default(false)')
debug: fp.int('debug', `d`, 0, 'prints blocks: 1=other, 2:+dirs, 3=+files, 4=+data, default(0=silent)')
max_blocks: fp.int('max_blocks', `m`, 0, 'maximum blocks to read, stop early. Default(0=read all)')
filename: fp.string('filename', `f`, '', 'filename content complete print, stop early. Default(empty means none)')
url: fp.string('url', `u`, default_url,
'archive *.tar.gz URL, default(${default_url}). Start name with file:/// for local')
chunks: fp.bool('chunks', `c`, false,
'decompress with chunks to reduce RAM usage, default(false)')
debug: fp.int('debug', `d`, 0,
'prints blocks: 1=other, 2:+dirs, 3=+files, 4=+data, default(0=silent)')
max_blocks: fp.int('max_blocks', `m`, 0,
'maximum blocks to read, stop early. Default(0=read all)')
filename: fp.string('filename', `f`, '',
'filename content complete print, stop early. Default(empty means none)')
}
additional := fp.finalize()!
if additional.len > 0 {
@@ -84,12 +89,6 @@ mut:
content []u8
}
fn new_file_reader(ctx &Context) FileReader {
return FileReader{
ctx: ctx
}
}
fn (mut f FileReader) other_block(mut read tar.Read, details string) {
if f.ctx.read_last_block(mut read) {
return
+4 -6
View File
@@ -127,8 +127,7 @@ fn (mut g Game) draw() {
ws := gg.window_size()
g.ctx.begin()
sgl.push_matrix()
sgl.scale(f32(ws.width) / f32(designed_width), f32(ws.height) / f32(designed_height),
0)
sgl.scale(f32(ws.width) / f32(designed_width), f32(ws.height) / f32(designed_height), 0)
g.draw_paddle()
g.draw_ball()
@@ -160,8 +159,7 @@ fn (g &Game) draw_paddle() {
roffset, rradius := -5, 18
g.ctx.draw_circle_filled(g.paddle_x - roffset, g.height, rradius, gg.blue)
g.ctx.draw_circle_filled(g.paddle_x + g.paddle_w + roffset, g.height, rradius, gg.blue)
g.ctx.draw_rect_filled(g.paddle_x, g.height - g.paddle_h + 2, g.paddle_w, g.paddle_h,
gg.blue)
g.ctx.draw_rect_filled(g.paddle_x, g.height - g.paddle_h + 2, g.paddle_w, g.paddle_h, gg.blue)
g.ctx.draw_rect_filled(g.paddle_x, g.height - g.paddle_h + 2, g.paddle_w, bevel_size,
highlight_color)
}
@@ -170,8 +168,8 @@ fn (g &Game) draw_brick(brick Brick) {
g.ctx.draw_rect_filled(brick.x, brick.y, brick.w, brick.h, brick.c)
g.ctx.draw_rect_filled(brick.x, brick.y, brick.w, bevel_size, highlight_color)
g.ctx.draw_rect_filled(brick.x, brick.y, bevel_size, brick.h - bevel_size, highlight_color)
g.ctx.draw_rect_filled(brick.x + brick.w - bevel_size, brick.y, bevel_size, brick.h - bevel_size,
shade_color)
g.ctx.draw_rect_filled(brick.x + brick.w - bevel_size, brick.y, bevel_size,
brick.h - bevel_size, shade_color)
g.ctx.draw_rect_filled(brick.x, brick.y + brick.h - bevel_size, brick.w, bevel_size,
shade_color)
}
+2 -1
View File
@@ -63,7 +63,8 @@ fn main() {
converter := C.wkhtmltopdf_create_converter(global_settings)
println('wkhtmltopdf_create_converter: ${voidptr(converter)}')
// convert
mut result := C.wkhtmltopdf_set_object_setting(object_settings, c'page', c'http://www.google.com.br')
mut result := C.wkhtmltopdf_set_object_setting(object_settings, c'page',
c'http://www.google.com.br')
println('wkhtmltopdf_set_object_setting: ${result} [page = http://www.google.com.br]')
C.wkhtmltopdf_add_object(converter, object_settings, 0)
println('wkhtmltopdf_add_object')
+2 -4
View File
@@ -50,15 +50,13 @@ fn on_frame(mut app App) {
app.gg.begin()
for i in 0 .. 60 { // draw minute tics
draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.minutes_tic, tic_color,
i * 6)
draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.minutes_tic, tic_color, i * 6)
}
for i in 0 .. 12 { // hours
draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.hours_tic, tic_color, i * 30)
}
for i in 0 .. 4 { // 3 hours
draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.hours3_tic, tic_color,
i * 90)
draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.hours3_tic, tic_color, i * 90)
}
n := time.now()
+4 -2
View File
@@ -86,8 +86,10 @@ fn main() {
vals: ['1', 'jackson', '']
}
response = db.exec_param_many('select * from users where username = ? and id = ?',
['bailey', '3'])!
response = db.exec_param_many('select * from users where username = ? and id = ?', [
'bailey',
'3',
])!
assert response[0] == mysql.Row{
vals: ['3', 'bailey', '']
}
@@ -12,8 +12,8 @@ pub mut:
}
pub fn (particle Particle) draw(mut ctx gg.Context) {
ctx.draw_circle_filled(particle.pos.x, get_params().height - particle.pos.y, get_params().particle_radius,
particle.color)
ctx.draw_circle_filled(particle.pos.x, get_params().height - particle.pos.y,
get_params().particle_radius, particle.color)
}
pub fn (mut particle Particle) tick(mut rocket Rocket, mut ctx gg.Context) {
+2 -2
View File
@@ -15,8 +15,8 @@ pub mut:
}
pub fn (rocket Rocket) draw(mut ctx gg.Context) {
ctx.draw_circle_filled(rocket.pos.x, get_params().height - rocket.pos.y, get_params().rocket_radius,
rocket.color)
ctx.draw_circle_filled(rocket.pos.x, get_params().height - rocket.pos.y,
get_params().rocket_radius, rocket.color)
}
pub fn (mut rocket Rocket) explode() {
+10 -9
View File
@@ -208,9 +208,12 @@ fn (mut app App) init_images_wrapper() {
fn (mut app App) init_images() ! {
app.bird = app.gg.create_image_from_byte_array(asset.read_bytes('assets', 'img/bird.png')!)!
app.pipetop = app.gg.create_image_from_byte_array(asset.read_bytes('assets', 'img/pipetop.png')!)!
app.pipebottom = app.gg.create_image_from_byte_array(asset.read_bytes('assets', 'img/pipebottom.png')!)!
app.background = app.gg.create_image_from_byte_array(asset.read_bytes('assets', 'img/background.png')!)!
app.pipetop =
app.gg.create_image_from_byte_array(asset.read_bytes('assets', 'img/pipetop.png')!)!
app.pipebottom = app.gg.create_image_from_byte_array(asset.read_bytes('assets',
'img/pipebottom.png')!)!
app.background = app.gg.create_image_from_byte_array(asset.read_bytes('assets',
'img/background.png')!)!
}
fn frame(app &App) {
@@ -230,20 +233,18 @@ fn (app &App) display() {
app.gg.draw_image(f32(pipe.x), f32(pipe.y + pipe.height - app.pipetop.height),
app.pipetop.width, app.pipetop.height, app.pipetop)
} else {
app.gg.draw_image(f32(pipe.x), f32(pipe.y), app.pipebottom.width, app.pipebottom.height,
app.pipebottom)
app.gg.draw_image(f32(pipe.x), f32(pipe.y), app.pipebottom.width,
app.pipebottom.height, app.pipebottom)
}
}
for bird in app.birds {
if bird.alive {
app.gg.draw_image(f32(bird.x), f32(bird.y), app.bird.width, app.bird.height,
app.bird)
app.gg.draw_image(f32(bird.x), f32(bird.y), app.bird.width, app.bird.height, app.bird)
}
}
app.gg.draw_rect_filled(0, 510, app.background.width * 3, 5, gg.Color{0x21, 0x19, 0x28, 255})
app.gg.draw_rect_filled(0, 513, app.background.width * 3, app.background.height, bg_color)
app.gg.draw_rect_filled(550, 0, app.background.width + 50, app.background.height + 20,
bg_color)
app.gg.draw_rect_filled(550, 0, app.background.width + 50, app.background.height + 20, bg_color)
app.gg.draw_text_def(10, 25, 'Score: ${app.score}')
app.gg.draw_text_def(10, 50, 'Max Score: ${app.max_score}')
app.gg.draw_text_def(10, 75, 'Generation: ${app.generation}')
-4
View File
@@ -4,10 +4,6 @@ import time
const cell = '█'
const nothing = ' '
const switches = {
cell: nothing
nothing: cell
}
const transformers = [nothing, cell]
struct Game {
+2 -2
View File
@@ -14,8 +14,8 @@ fn print_automaton(app &App) {
for x := 1; x < app.a.field.maxx; x++ {
cell := app.a.field.get(x, y)
if cell == 1 {
app.gg.draw_rect_filled(f32(square_size * x), f32(square_size * y), f32(square_size),
f32(square_size), filled_color)
app.gg.draw_rect_filled(f32(square_size * x), f32(square_size * y),
f32(square_size), f32(square_size), filled_color)
}
}
}
@@ -80,8 +80,8 @@ pub fn (mut aa Automaton) update() {
for y := 1; y < aa.field.maxy; y++ {
for x := 1; x < aa.field.maxx; x++ {
moore_sum := (0 + aa.field.get(x - 1, y - 1) + aa.field.get(x, y - 1) + aa.field.get(x +
1, y - 1) + aa.field.get(x - 1, y) + 0 + aa.field.get(x + 1, y) +
aa.field.get(x - 1, y + 1) + aa.field.get(x, y + 1) + aa.field.get(x + 1, y + 1))
1, y - 1) + aa.field.get(x - 1, y) + 0 + aa.field.get(x + 1, y) + aa.field.get(x -
1, y + 1) + aa.field.get(x, y + 1) + aa.field.get(x + 1, y + 1))
cell := aa.field.get(x, y)
v := if cell == 1 { moore_sum in [2, 3] } else { moore_sum == 3 }
aa.new_field.set(x, y, if v { 1 } else { 0 })
+4 -5
View File
@@ -111,8 +111,7 @@ fn (mut g Game) header() {
}
fn (mut g Game) board() {
g.ctx.draw_rect_filled(pad - 8, head - 8, board_px + 16, board_px + 16, gg.rgb(218,
206, 188))
g.ctx.draw_rect_filled(pad - 8, head - 8, board_px + 16, board_px + 16, gg.rgb(218, 206, 188))
for i, v in g.board {
if g.anim && i == g.from {
continue
@@ -123,10 +122,10 @@ fn (mut g Game) board() {
if g.anim {
x0, y0 := xy(g.from)
x1, y1 := xy(g.to)
g.tile(int(f32(x0) + f32(x1 - x0) * g.t), int(f32(y0) + f32(y1 - y0) * g.t), g.val,
false)
g.tile(int(f32(x0) + f32(x1 - x0) * g.t), int(f32(y0) + f32(y1 - y0) * g.t), g.val, false)
}
g.ctx.draw_text(pad, head + board_px + 22, 'Arrow keys / WASD or click a tile next to the empty space.',
g.ctx.draw_text(pad, head + board_px + 22,
'Arrow keys / WASD or click a tile next to the empty space.',
size: 16
color: wcolor
)
+6 -3
View File
@@ -117,9 +117,12 @@ fn on_frame(mut app App) {
y += 150
app.gg.draw_text_def(10, y + 20, 'Use arrow keys to increase/decrease number of segments.')
app.gg.draw_text_def(10, y + 36, 'Use the mouse to adjust the start/end angles, in radians. Mouse position (0,0) is at the top-left of the window.')
app.gg.draw_text_def(10, y + 52, 'Note: because y=0 is at the top of the screen and not the bottom, angle=0 is at the bottom of an arc, not the top!')
app.gg.draw_text_def(10, y + 68, 'Compared to a graph, where y=0 is at the bottom, arcs therefore appear y-flipped.')
app.gg.draw_text_def(10, y + 36,
'Use the mouse to adjust the start/end angles, in radians. Mouse position (0,0) is at the top-left of the window.')
app.gg.draw_text_def(10, y + 52,
'Note: because y=0 is at the top of the screen and not the bottom, angle=0 is at the bottom of an arc, not the top!')
app.gg.draw_text_def(10, y + 68,
'Compared to a graph, where y=0 is at the bottom, arcs therefore appear y-flipped.')
app.gg.end()
}
+3 -3
View File
@@ -82,7 +82,8 @@ fn frame(mut app App) {
update_rain_column(mut rc, app.cols, app.rows)
draw_rain_column(rc, app)
}
app.ctx.draw_text(app.screen_size.width / 2 - 190, app.screen_size.height - 15, 'press `f` to toggle fullscreen, Up/Down arrows to change speed',
app.ctx.draw_text(app.screen_size.width / 2 - 190, app.screen_size.height - 15,
'press `f` to toggle fullscreen, Up/Down arrows to change speed',
color: gg.gray
)
app.ctx.end()
@@ -149,8 +150,7 @@ fn draw_rain_column(rc RainColumn, app App) {
}
if i < rc.drops.len {
app.ctx.draw_text(x, y, rc.drops[i].ascii_str(), cfg)
app.ctx.draw_text(x, y, rc.drops[(i + 10) % rc.drops.len].ascii_str(),
cfg)
app.ctx.draw_text(x, y, rc.drops[(i + 10) % rc.drops.len].ascii_str(), cfg)
} else {
vprintln('BAD i: ${i} | rc.drops.len: ${rc.drops.len}')
}
+3 -3
View File
@@ -60,8 +60,7 @@ fn (mut app App) draw_circle(label string, f easing.EasingFN) {
offset := 30
app.gg.draw_text_def(int(app.x) - 30, 5, label)
app.gg.draw_line(f32(app.x), offset, f32(app.x), f32(app.h + offset), gg.gray)
app.gg.draw_circle_filled(f32(app.x), f32(offset + f(app.t) * app.h), 10, gg.rgb(0,
0, 255))
app.gg.draw_circle_filled(f32(app.x), f32(offset + f(app.t) * app.h), 10, gg.rgb(0, 0, 255))
app.x += 120
}
@@ -77,7 +76,8 @@ fn (mut app App) frame() {
for k, e in current_map {
app.draw_circle(k, e)
}
app.gg.draw_text_def(50, int(app.h + 50), 'Note: use left and right arrows to change functions. Frame: ${app.gg.frame:010} | t: ${app.t:6.3f} | kind: ${app.kind}.')
app.gg.draw_text_def(50, int(app.h + 50),
'Note: use left and right arrows to change functions. Frame: ${app.gg.frame:010} | t: ${app.t:6.3f} | kind: ${app.kind}.')
app.gg.end()
}
+1
View File
@@ -86,6 +86,7 @@ fn (mut app App) draw() {
for y, row in app.buf {
for x, i in row {
app.gg.draw_square_filled(t * width * scale + x * scale,
(size.height - height * scale) + y * scale, scale, palette[i])
}
}
+2 -2
View File
@@ -13,7 +13,6 @@ const cmax_y = 81
const cs = 10
const c_fg = gg.rgb(20, 30, 255)
const c_em = gg.rgb(255, 50, 0)
fn main() {
mut app := &App{}
@@ -64,7 +63,8 @@ fn frame(app &App) {
for y in 0 .. cmax_y {
for x in 0 .. cmax_x {
cy, cx := y * cs, x * cs
app.gg.draw_rect_empty_no_context(cx + 2, cy + 2, cs - 3, cs - 3, c_em)
app.gg.draw_rect_empty_no_context(cx + 2, cy + 2, cs - 3, cs - 3,
gg.rgb(255, 50, 0))
}
}
sgl.end()
@@ -84,7 +84,8 @@ fn main() {
event_fn: on_event // it calls on every event
user_data: app // store user data
)
mut grid := initialise_grid() // initialize the grid variable and populate the matrix with each cell as empty
mut grid :=
initialise_grid() // initialize the grid variable and populate the matrix with each cell as empty
app.grid = grid // set grid to app attribute so you can access it by just passing app variable or with method of app
app.ui.dpi_scale = 1.0 // set scale this is use to make it responsive
app.start = &Point{ // set start point to -1, -1
@@ -452,11 +453,3 @@ fn (mut heap MinHeap) right_child(idx int) !int {
fn (mut heap MinHeap) parent(idx int) int {
return (idx - 1) / 2
}
// comaparator of heap //TODO not used
fn comparator(n1 Node, n2 Node) bool {
if n1.f_score == n2.f_score {
return n1.count > n2.count
}
return n1.f_score > n2.f_score
}
+3 -3
View File
@@ -142,8 +142,7 @@ fn on_frame(data voidptr) {
}
// Draw paddles
app.ctx.draw_rounded_rect_filled(20, app.p1_y, app.paddle_width, app.paddle_height,
5, color_p1)
app.ctx.draw_rounded_rect_filled(20, app.p1_y, app.paddle_width, app.paddle_height, 5, color_p1)
app.ctx.draw_rounded_rect_filled(f32(app.width) - 20 - app.paddle_width, app.p2_y,
app.paddle_width, app.paddle_height, 5, color_p2)
@@ -198,7 +197,8 @@ fn on_frame(data voidptr) {
align: .center
)
} else {
app.ctx.draw_text(app.width / 2, app.height - 25, 'SPACE: Pause | W/S: P1 | UP/DOWN: P2 | R: Reset',
app.ctx.draw_text(app.width / 2, app.height - 25,
'SPACE: Pause | W/S: P1 | UP/DOWN: P2 | R: Reset',
size: 16
color: color_text_dim
align: .center
+3 -3
View File
@@ -15,7 +15,6 @@ import gg
import math
const player_size = 8
const player_move_delta = 10
const map_x_size = 8
const map_y_size = 8
const map_square = 64
@@ -79,8 +78,8 @@ fn draw_map_2d(app App) {
for y := 0; y < map_y_size; y++ {
for x := 0; x < map_x_size; x++ {
color := if app.map[y * map_x_size + x] == 1 { gg.white } else { gg.black }
app.ctx.draw_rect_filled(x * map_square, y * map_square, map_square - 1, map_square - 1,
color)
app.ctx.draw_rect_filled(x * map_square, y * map_square, map_square - 1,
map_square - 1, color)
}
}
}
@@ -215,6 +214,7 @@ fn draw_rays_and_walls(app App) {
wall_height := math.min((map_square * max_wall_height) / distance, max_wall_height)
wall_offset := max_wall_height / 2 - wall_height / 2
app.ctx.draw_line_with_config(step * line_thickeness + offset_3d_view, wall_offset,
step * line_thickeness + offset_3d_view, wall_offset + wall_height, gg.PenConfig{
color: color
thickness: line_thickeness
+4 -3
View File
@@ -60,10 +60,11 @@ gg.start(
x += pdj[j] * math.sin(a - t) * cd600
y += pdj[j] * math.cos(a - t) * cd600
}
ctx.draw_rect_filled(f32(wsize.width / 2 + scale * x), f32(wsize.height / 2 + scale * y),
1, 1, colors[i % colors.len])
ctx.draw_rect_filled(f32(wsize.width / 2 + scale * x),
f32(wsize.height / 2 + scale * y), 1, 1, colors[i % colors.len])
}
ctx.draw_text(wsize.width / 2 - 170, wsize.height - 15, 'frame: ${ctx.frame:06}, k: ${k:4}, scale: ${scale:4}, arrows to change',
ctx.draw_text(wsize.width / 2 - 170, wsize.height - 15,
'frame: ${ctx.frame:06}, k: ${k:4}, scale: ${scale:4}, arrows to change',
color: colors[1]
)
ctx.end(how: .passthru)
-1
View File
@@ -11,7 +11,6 @@ import time
const win_width = 600
const win_height = 700
const bg_color = gg.white
const count_color = gg.black
struct App {
mut:
+3 -4
View File
@@ -52,10 +52,9 @@ fn frame(mut game Game) {
game.gg.begin()
game.gg.draw_text_def(10, 5, 'Modify examples/hot_reload/bounce.v to get instant updates')
game.gg.draw_rect_filled(game.x, game.y, width, width, gg.black)
game.gg.draw_rect_filled(window_width - width - game.x + 10, 200 - game.y + width,
width, width, gg.rgb(228, 10, 55))
game.gg.draw_rect_filled(game.x - 25, 250 - game.y, width, width, gg.rgb(28, 240,
55))
game.gg.draw_rect_filled(window_width - width - game.x + 10, 200 - game.y + width, width,
width, gg.rgb(228, 10, 55))
game.gg.draw_rect_filled(game.x - 25, 250 - game.y, width, width, gg.rgb(28, 240, 55))
game.gg.end()
}
Loaded 100 of 634 files, more files were not shown because too many files have changed in this diff. Show more