From e201665e9241e44712d09377781e1525c095c23b Mon Sep 17 00:00:00 2001 From: Ben <89769190+benwalksaway@users.noreply.github.com> Date: Thu, 2 Jun 2022 06:09:46 +0200 Subject: [PATCH] os: fix file_ext function (#14566) --- vlib/os/os.v | 14 +++++++++++++- vlib/os/os_test.v | 12 +++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/vlib/os/os.v b/vlib/os/os.v index b7574fc646..da38aa89be 100644 --- a/vlib/os/os.v +++ b/vlib/os/os.v @@ -173,8 +173,20 @@ pub fn is_dir_empty(path string) bool { // file_ext will return the part after the last occurence of `.` in `path`. // The `.` is included. +// Examples: +// ```v +// assert os.file_ext('file.v') == '.v' +// assert os.file_ext('.ignore_me') == '' +// assert os.file_ext('.') == '' +// ``` pub fn file_ext(path string) string { - pos := path.last_index('.') or { return '' } + if path.len < 3 { + return empty_str + } + pos := path.last_index(dot_str) or { return empty_str } + if pos + 1 >= path.len || pos == 0 { + return empty_str + } return path[pos..] } diff --git a/vlib/os/os_test.v b/vlib/os/os_test.v index 1782c7d16f..c685ac745d 100644 --- a/vlib/os/os_test.v +++ b/vlib/os/os_test.v @@ -585,9 +585,19 @@ fn test_is_executable_writable_readable() ? { os.rm(file_name) or { panic(err) } } -fn test_ext() { +fn test_file_ext() { assert os.file_ext('file.v') == '.v' + assert os.file_ext('file.js.v') == '.v' + assert os.file_ext('file.ext1.ext2.ext3') == '.ext3' + assert os.file_ext('.ignore_me.v') == '.v' assert os.file_ext('file') == '' + assert os.file_ext('.git') == '' + assert os.file_ext('file.') == '' + assert os.file_ext('.') == '' + assert os.file_ext('..') == '' + assert os.file_ext('file...') == '' + assert os.file_ext('.file.') == '' + assert os.file_ext('..file..') == '' } fn test_join() {