This file manager has a code snippet that handles an argument of the "cd" console command. It converts the argument to a valid path, expands ~ and environment variables into the corresponding values:
std::vector<unicode_t> ConvertCDArgToPath( const unicode_t* p )
{
std::vector<unicode_t> Out;
std::vector<unicode_t> Temp;
while ( p && *p )
{
unicode_t Ch = 0;
if ( *p == '~' )
{
if ( LookAhead( p, &Ch ) )
{
if ( ( IsPathSeparator(Ch) || Ch == 0 ) && ApplyEnvVariable( "HOME", &Temp ) )
{
// replace ~ with the HOME path
Out.insert( Out.end(), Temp.begin(), Temp.end() );
PopLastNull( &Out );
}
}
}
else if ( *p == '$' )
{
// skip `$`
std::vector<char> EnvVarName = unicode_to_utf8( p+1 );
for ( auto i = EnvVarName.begin(); i != EnvVarName.end(); i++ )
{
if ( IsPathSeparator( *i ) )
{
*i = 0;
break;
}
}
if ( ApplyEnvVariable( EnvVarName.data( ), &Temp ) )
{
// replace the var name with its value
Out.insert( Out.end(), Temp.begin(), Temp.end() );
PopLastNull( &Out );
// skip var name
p += strlen( EnvVarName.data() );
}
}
else if ( IsPathSeparator(*p) )
{
if ( !LastCharEquals( Out, '/' ) && !LastCharEquals( Out, '\\' ) ) Out.push_back( DIR_SPLITTER );
}
else
{
Out.push_back( *p );
}
p++;
}
Out.push_back( 0 );
return Out;
}
bool LookAhead( const unicode_t* p, unicode_t* OutNextChar )
{
if ( !p ) return false;
if ( !*p ) return false;
if ( OutNextChar ) *OutNextChar = *(p+1);
return true;
}
- Is this code secure?
- What is missing?
- How can I deal with the duplicate code around the
ApplyEnvVariable()
calls?
~
expanded by the shell automatically when used as parameter? \$\endgroup\$cd
command internally to switch to the desired folder. I.e.cd ~/Projects/$PROJNAME/data
should work. \$\endgroup\$Is this code secure?
\$\endgroup\$