@@ -5,26 +5,55 @@ const args = process.argv.slice(2);
55
66const showHidden = args . includes ( "-a" ) ;
77
8- const paths = args . filter ( ( arg ) => ! arg . startsWith ( "-" ) ) ;
9-
10- const targetPath = paths . length > 0 ? paths [ 0 ] : process . cwd ( ) ;
11-
12- let entries = await fs . readdir ( targetPath ) ;
13-
14- if ( ! showHidden ) {
15- entries = entries . filter ( ( entry ) => ! entry . startsWith ( "." ) ) ;
8+ const supportedFlags = [ "-1" , "-a" ] ;
9+ const unknownFlags = args . filter (
10+ ( arg ) => arg . startsWith ( "-" ) && ! supportedFlags . includes ( arg ) ,
11+ ) ;
12+
13+ if ( unknownFlags . length > 0 ) {
14+ console . error ( `ls: invalid option -- ' ${ unknownFlags [ 0 ] . slice ( 1 ) } '` ) ;
15+ process . exit ( 1 ) ;
1616}
1717
18- if ( showHidden ) {
19- entries = [ "." , ".." , ...entries ] ;
20- }
21-
22- entries . sort ( ( a , b ) => {
23- const cleanA = a . replace ( / ^ \. + / , "" ) ;
24- const cleanB = b . replace ( / ^ \. + / , "" ) ;
25- return cleanA . localeCompare ( cleanB ) ;
26- } ) ;
18+ const paths = args . filter ( ( arg ) => ! arg . startsWith ( "-" ) ) ;
2719
28- for ( const entry of entries ) {
29- process . stdout . write ( entry + "\n" ) ;
20+ const targetPaths = paths . length > 0 ? paths : [ process . cwd ( ) ] ;
21+
22+ for ( const targetPath of targetPaths ) {
23+ if ( targetPaths . length > 1 ) {
24+ process . stdout . write ( `${ targetPath } :\n` ) ;
25+ }
26+
27+ let entries ;
28+
29+ try {
30+ entries = await fs . readdir ( targetPath ) ;
31+ } catch ( error ) {
32+ console . error (
33+ `ls: cannot access '${ targetPath } ': No such file or directory` ,
34+ ) ;
35+ continue ;
36+ }
37+
38+ if ( ! showHidden ) {
39+ entries = entries . filter ( ( entry ) => ! entry . startsWith ( "." ) ) ;
40+ }
41+
42+ if ( showHidden ) {
43+ entries = [ "." , ".." , ...entries ] ;
44+ }
45+
46+ entries . sort ( ( a , b ) => {
47+ const cleanA = a . replace ( / ^ \. + / , "" ) ;
48+ const cleanB = b . replace ( / ^ \. + / , "" ) ;
49+ return cleanA . localeCompare ( cleanB ) ;
50+ } ) ;
51+
52+ for ( const entry of entries ) {
53+ process . stdout . write ( entry + "\n" ) ;
54+ }
55+
56+ if ( targetPaths . length > 1 ) {
57+ process . stdout . write ( "\n" ) ;
58+ }
3059}
0 commit comments