11import { argv } from './argv'
2- import { OptionReader } from './types'
2+ import { OptionReader , OptionResult } from './types'
33import { Merge , ReturnTypes , UnionMerge } from './utils'
44
55function isOption ( arg : string ) {
@@ -17,7 +17,7 @@ function createOptionReader<T extends OptionReader[]>(optionReaders: [...T]) {
1717 return readOption
1818 }
1919
20- return ( option , next , options ) => readOption ( option , next , options ) ?? readNextOption ( option , next , options )
20+ return ( option , read , options ) => readOption ( option , read , options ) ?? readNextOption ( option , read , options )
2121 } ,
2222 null
2323 )
@@ -31,18 +31,31 @@ function createOptionReader<T extends OptionReader[]>(optionReaders: [...T]) {
3131 * @returns Options with values.
3232 */
3333export function readOptions < T extends OptionReader [ ] > ( ...optionReaders : [ ...T ] ) : Partial < Merge < ReturnTypes < T > > > {
34- if ( ! argv . length || ! optionReaders . length ) {
34+ if ( ! argv . length ) {
3535 return { }
3636 }
3737
3838 const readOption = createOptionReader ( optionReaders )
39+
40+ if ( ! readOption ) {
41+ return { }
42+ }
43+
3944 const options = { }
4045 let i = 0
4146 let arg = argv [ i ]
42- const next = ( required = false ) => {
47+ let optionResult : OptionResult | null
48+ const next = ( ) => {
4349 arg = argv [ ++ i ]
50+ }
51+ const remove = ( ) => {
52+ argv . splice ( i -- , 1 )
53+ }
54+ const read = ( ) => {
55+ next ( )
56+ remove ( )
4457
45- if ( required && ! arg ) {
58+ if ( ! arg ) {
4659 throw new Error ( 'Unexpected end of arguments' )
4760 }
4861
@@ -52,7 +65,12 @@ export function readOptions<T extends OptionReader[]>(...optionReaders: [...T]):
5265 // eslint-disable-next-line no-unmodified-loop-condition
5366 while ( arg ) {
5467 if ( isOption ( arg ) ) {
55- Object . assign ( options , readOption ?.( removePrefix ( arg ) , next , options ) )
68+ optionResult = readOption ( removePrefix ( arg ) , read , options )
69+
70+ if ( optionResult ) {
71+ remove ( )
72+ Object . assign ( options , optionResult )
73+ }
5674 }
5775
5876 next ( )
0 commit comments