# HG changeset patch # User Elie De Brauwer # Date 1329052498 -3600 # Node ID 6c62d5b6675a045b5be848d042c5eb87ef70bcba # Parent 8f5780dd6da4696d10136e5a72de5be51700523e Add test for basename, fix issue where suffix is wrongfully applied if it appears in the middle of the filename diff -r 8f5780dd6da4 -r 6c62d5b6675a scripts/test/basename.test --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/scripts/test/basename.test Sun Feb 12 14:14:58 2012 +0100 @@ -0,0 +1,23 @@ +#!/bin/bash + +[ -f testing.sh ] && . testing.sh + +#testing "name" "command" "result" "infile" "stdin" + +# Removal of extra /'s +testing "basename /-only" "basename ///////" "/\n" "" "" +testing "basename trailing /" "basename a//////" "a\n" "" "" +testing "basename combined" "basename /////a///b///c///d/////" "d\n" "" "" + +# Standard suffix behavior. +testing "basename suffix" "basename a/b/c/d.suffix .suffix" "d\n" "" "" + +# A suffix cannot be the entire result. +testing "basename suffix=result" "basename .txt .txt" ".txt\n" "" "" + +# Deal with suffix appearing in the filename +testing "basename reappering suffix 1" "basename a.txt.txt .txt" "a.txt\n" "" "" +testing "basename reappering suffix 2" "basename a.txt.old .txt" "a.txt.old\n" "" "" + +# A suffix should be a real suffix, only a the end. +testing "basename invalid suffix" "basename isthisasuffix? suffix" "isthisasuffix?\n" "" "" \ No newline at end of file diff -r 8f5780dd6da4 -r 6c62d5b6675a toys/basename.c --- a/toys/basename.c Mon Feb 13 08:44:32 2012 -0600 +++ b/toys/basename.c Sun Feb 12 14:14:58 2012 +0100 @@ -15,7 +15,7 @@ help usage: basename string [suffix] - Return non-directory portion of a pathname + Return non-directory portion of a pathname removing suffix */ #include "toys.h" @@ -37,9 +37,11 @@ // chop off the suffix if provided if (suffix) { - char *s = strstr(base, suffix); - if (s && s != base) *s = 0; + int suflen = strlen(suffix); + int reslen = strlen(base); + if (suflen < reslen && !strcmp( base+reslen-suflen, suffix)) + base[reslen-suflen] = 0; } - + puts(base); }