Commit 89dda365 authored by jan.koester's avatar jan.koester
Browse files

sh: git's shell commands run (octopus, resolve, filter-branch, mergetool)

- a function defined inside if/while/case: its "{" (after "name()") is
  counted like its "}", so the enclosing construct no longer ends early
- heredoc delimiters quoted with a backslash ("<< \EOF") or partly quoted
- "${#name}", "${#}"
- "v=$(cmd)" returns cmd's exit status ("if v=$(git write-tree)")
- "$({ ...; } | sort)" inside a function body: the substitution's braces
  are its own
- comments inside "cmd | { ...; }" groups: an apostrophe in them is no
  quote
- "type" builtin; "command -v/-V" know shell functions

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent edc7c1d6
Loading
Loading
Loading
Loading
+45 −4
Changes for commands/shell/command.cpp: 45 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -65,7 +65,16 @@ namespace fresh { namespace cmd {
        // builtin/applet name (found=true, resolved=NAME itself, matching
        // real shells printing just the bare name for builtins), else a
        // PATH search (containing '/' uses NAME directly, never searched).
        static bool resolve(const std::string &name,std::string &resolved,bool &isBuiltin){
        static bool resolve(const std::string &name,std::string &resolved,bool &isBuiltin,
                            bool *isFunction=nullptr){
            if(isFunction) *isFunction=false;
            // a shell function: "command -v f" prints its name
            if(Shell::instance().find(name)==nullptr && Shell::instance().hasFunction(name)){
                isBuiltin=false;
                if(isFunction) *isFunction=true;
                resolved=name;
                return true;
            }
            isBuiltin=(Shell::instance().find(name)!=nullptr);
            if(isBuiltin){
                resolved=name;
@@ -111,14 +120,15 @@ namespace fresh { namespace cmd {
                for(; i<argc; ++i){
                    std::string name=argv[i];
                    std::string resolved;
                    bool isBuiltin=false;
                    if(!resolve(name,resolved,isBuiltin)){
                    bool isBuiltin=false,isFunction=false;
                    if(!resolve(name,resolved,isBuiltin,&isFunction)){
                        allFound=false;
                        continue;
                    }
                    if(verbose){
                        std::cout << name << " is "
                                   << (isBuiltin ? "a shell builtin" : resolved)
                                   << (isFunction ? "a shell function" :
                                       isBuiltin ? "a shell builtin" : resolved)
                                   << std::endl;
                    }else{
                        std::cout << resolved << std::endl;
@@ -136,4 +146,35 @@ namespace fresh { namespace cmd {

    FRESH_REGISTER_COMMAND(CommandCommand);

    // "type NAME...": how NAME would be run -- a shell function, a builtin
    // or a PATH program (git-mergetool--lib's is_available: type "$tool"
    // >/dev/null 2>&1). Status 1 if any NAME is not found.
    class TypeCommand : public ShellCommand {
    public:
        TypeCommand():ShellCommand("type"){}

        int runCommand(int argc,const char **argv){
            int rc=0;
            for(int i=1;i<argc;++i){
                std::string name=argv[i];
                std::string resolved;
                bool isBuiltin=false,isFunction=false;
                if(!CommandCommand::resolve(name,resolved,isBuiltin,&isFunction)){
                    std::cerr << "type: " << name << ": not found" << std::endl;
                    rc=1;
                    continue;
                }
                if(isFunction)
                    std::cout << name << " is a shell function" << std::endl;
                else if(isBuiltin)
                    std::cout << name << " is a shell builtin" << std::endl;
                else
                    std::cout << name << " is " << resolved << std::endl;
            }
            return rc;
        }
    };

    FRESH_REGISTER_COMMAND(TypeCommand);

}}
+32 −0
Changes for src/envoirment.cpp: 32 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -547,6 +547,38 @@ std::string fresh::Environment::expand(const std::string &token){
            continue;
        }

        // "${#name}" / "${#1}": length of the value (git's
        // git-filter-branch); "${#}", "${#@}", "${#*}": number of
        // positional parameters
        if(i+2<token.length() && token[i+1]=='{' && token[i+2]=='#'){
            size_t close=token.find('}',i+3);
            if(close!=std::string::npos){
                std::string name=token.substr(i+3,close-(i+3));
                bool isName=!name.empty();
                for(size_t k=0;k<name.size();++k)
                    if(!(isalnum((unsigned char)name[k]) || name[k]=='_'))
                        isName=false;
                if(name.empty() || name=="@" || name=="*"){
                    result+=std::to_string(_positionalArgs.size());
                    i=close;
                    continue;
                }
                if(isName){
                    std::string v;
                    if(isdigit((unsigned char)name[0])){
                        size_t idx=(size_t)atoi(name.c_str());
                        if(idx==0) v=_scriptName;
                        else if(idx<=_positionalArgs.size()) v=_positionalArgs[idx-1];
                    }else{
                        getVariable(name,v);
                    }
                    result+=std::to_string(v.size());
                    i=close;
                    continue;
                }
            }
        }

        // "${0}"/"${1}".."${9}" -- the braced spelling of "$0"/"$1".."$9"
        // just below. Checked FIRST (before the bare/unbraced forms, and
        // well before the generic "${name}" path much further down) since
+79 −8
Changes for src/shell.cpp: 79 added lines, 8 removed lines.
Original line number Diff line number Diff line
@@ -1389,6 +1389,23 @@ std::vector<fresh::ShellWord> fresh::tokenizeShellWords(const std::string &input
    return words;
}

// A heredoc delimiter word with its quoting removed: "\EOF" (git's
// git-filter-branch: functions=$(cat << \EOF ...)), "E'O'F", "'EOF'" all
// mean EOF. True if any quoting was present -- POSIX: then the body is
// taken literally, no expansion.
static bool stripHeredocQuoting(std::string &w){
    std::string out;
    bool quoted=false;
    for(size_t i=0;i<w.size();++i){
        char c=w[i];
        if(c=='\\' && i+1<w.size()){ out+=w[++i]; quoted=true; continue; }
        if(c=='\'' || c=='"'){ quoted=true; continue; }
        out+=c;
    }
    w=out;
    return quoted;
}

std::string fresh::heredocMarkerDelim(const std::vector<ShellWord> &words,size_t i,size_t &consumed){
    consumed=1;
    if(i>=words.size())
@@ -1408,7 +1425,9 @@ std::string fresh::heredocMarkerDelim(const std::vector<ShellWord> &words,size_t
            while(p<w.size() && w[p]!=q) ++p;
            return w.substr(start,p-start);
        }
        return w.substr(p);
        std::string d=w.substr(p);
        stripHeredocQuoting(d);
        return d;
    }
    // Split form: "<<"/"<<-" alone (whitespace ended the word right
    // there) -- the delimiter is the NEXT word entirely.
@@ -1418,7 +1437,9 @@ std::string fresh::heredocMarkerDelim(const std::vector<ShellWord> &words,size_t
        if(d.size()>=2 &&
           ((d.front()=='\'' && d.back()=='\'') || (d.front()=='"' && d.back()=='"')))
            return d.substr(1,d.size()-2);
        return d;
        std::string u=d;
        stripHeredocQuoting(u);
        return u;
    }
    return "";
}
@@ -1462,6 +1483,14 @@ std::string fresh::shellWordsRawText(const std::string &input,const std::vector<
    return input.substr(start,end-start);
}

// "name()" / "()": the word before a function body's "{", which is a real
// opener there (a function defined inside an if/while/case body, e.g. git's
// git-sh-setup: "if ...; then\n\tusage() {\n...\n\t}\n...fi"). Without it
// only the body's "}" was counted, closing the enclosing construct early.
static bool endsWithFnParens(const std::string &t){
    return t.size()>=2 && t.compare(t.size()-2,2,"()")==0;
}

// True if words[at] starts a compound command (if/for/while/{/!) rather
// than a plain simple command -- see the set -e comments in parse() where
// this decides whether that segment's returned status is re-tested against
@@ -1479,6 +1508,7 @@ fresh::Shell::Shell(){
    _lastShellCommand=nullptr;
    _running=true;
    _exitCode=0;
    _lastSubstStatus=-1;
    _runningTraps=false;
    _exitTrapRun=false;
    _errexit=false;
@@ -2135,6 +2165,8 @@ std::string fresh::Shell::runCaptured(const std::string &cmd){

    int status=0;
    waitpid(pid,&status,0);
    _lastSubstStatus=WIFEXITED(status) ? WEXITSTATUS(status)
                    : WIFSIGNALED(status) ? 128+WTERMSIG(status) : 1;

    size_t end=output.find_last_not_of('\n');
    return (end==std::string::npos) ? "" : output.substr(0,end+1);
@@ -2281,6 +2313,16 @@ std::vector<std::string> fresh::splitPipelineStages(const std::string &segment,
            continue;
        }

        // a comment runs to the end of its line: an apostrophe in it
        // ("# ... don't ...", git-mergetool--lib) is no quote
        if(c=='#' && (i==0 || strchr(" \t\n;",segment[i-1]))){
            size_t e=segment.find('\n',i);
            if(e==std::string::npos) e=n;
            current.append(segment,i,e-i);
            i=e;
            continue;
        }

        if(c=='\'' || c=='"'){
            char q=c;
            current+=c;
@@ -2387,6 +2429,7 @@ std::vector<std::string> fresh::splitPipelineStages(const std::string &segment,
                      segment[j]!='|' && segment[j]!='<' && segment[j]!='>' && segment[j]!='\n')
                    ++j;
                word=segment.substr(wordstart,j-wordstart);
                stripHeredocQuoting(word);
            }

            current += segment.substr(markerstart,j-markerstart);
@@ -2512,6 +2555,12 @@ bool fresh::extractBraceGroupBody(const std::string &stage,std::string &body,std
    int depth=1;
    while(j<n && depth>0){
        char c=stage[j];
        if(c=='#' && strchr(" \t\n;",stage[j-1])){
            // comment: to the end of the line (see splitPipelineStages())
            size_t e=stage.find('\n',j);
            j=(e==std::string::npos) ? n : e;
            continue;
        }
        if(c=='\'' || c=='"'){
            char q=c;
            ++j;
@@ -2661,6 +2710,8 @@ bool fresh::needsMoreInput(const std::string &text){
        if(p==0) return true;
        char c=text[p-1];
        if(c==';' || c=='\n' || c=='|') return true;
        // "name() {" / "name () {": a function body's opening brace
        if(c==')' && p>=2 && text[p-2]=='(') return true;
        if(c=='&' && p>=2 && text[p-2]=='&') return true;
        // "if"/"elif"/"while" right before `pos` also opens a real command
        // position: their own CONDITION is a command like any other, and
@@ -2755,6 +2806,7 @@ bool fresh::needsMoreInput(const std::string &text){
                      text[j]!=';' && text[j]!='&' && text[j]!='|' && text[j]!='>')
                    ++j;
                delim=text.substr(start,j-start);
                stripHeredocQuoting(delim);
            }
            if(!delim.empty()){
                inHeredoc=true;
@@ -2781,6 +2833,15 @@ bool fresh::needsMoreInput(const std::string &text){
        // extractSubshellBody()'s/tokenizeShellWords()'s own char-level
        // "(...)" depth scan has for a case statement nested inside a
        // subshell.
        // An unquoted "$(...)" is one unit: braces/keywords inside it
        // (git-mergetool--lib: v=$({ ...; } | sort) in a function body)
        // belong to the substitution, not to the construct around it.
        if(c=='$' && i+1<n && text[i+1]=='(' && !(i+2<n && text[i+2]=='(')){
            size_t close=cmdSubstClose(text,i+2);
            if(close>=n) return true;
            i=close+1;
            continue;
        }
        if(c=='('){ ++parenDepth; ++i; continue; }
        if(c==')'){ if(parenDepth>0) --parenDepth; ++i; continue; }

@@ -3100,6 +3161,8 @@ bool fresh::extractHeredocSpec(std::string &text,fresh::HeredocSpec &spec){
                      text[j]!='|' && text[j]!='<' && text[j]!='>')
                    ++j;
                word=text.substr(wordstart,j-wordstart);
                if(stripHeredocQuoting(word))
                    quoted=true;
            }

            if(word.empty())
@@ -3346,6 +3409,7 @@ std::string fresh::Shell::collectHeredocBodyFromText(const std::string &rawLines
}

int fresh::Shell::runSimple(const std::string &segment){
    _lastSubstStatus=-1;
    std::vector<std::string> inlineHeredocBodies;
    std::vector<std::string> rawstages=splitPipelineStages(segment,inlineHeredocBodies);

@@ -3486,7 +3550,9 @@ int fresh::Shell::runSimple(const std::string &segment){
            // its own to however many leading assignments there are.
            for(size_t k=0; k<assignments.size(); ++k)
                Environment::instance().setVariable(assignments[k].first,assignments[k].second);
            return 0;
            // POSIX 2.9.1: the status of the last command substitution
            // ("if v=$(git write-tree 2>/dev/null)" in git-merge-resolve)
            return _lastSubstStatus>=0 ? _lastSubstStatus : 0;
        }

        // "FOO=bar cmd args...": POSIX's prefix-assignment form (rpm's own
@@ -3924,7 +3990,8 @@ int fresh::Shell::runSegmentWords(const std::string &input,const std::vector<She
                            words[i-1].text=="||" || words[i-1].text=="|" || words[i-1].text=="do" ||
                            words[i-1].text=="then" || words[i-1].text=="else" ||
                            words[i-1].text=="if" || words[i-1].text=="elif" ||
                            words[i-1].text=="while" || words[i-1].text=="until" || words[i-1].text=="!" || words[i-1].text=="{");
                            words[i-1].text=="while" || words[i-1].text=="until" || words[i-1].text=="!" || words[i-1].text=="{" ||
                           endsWithFnParens(words[i-1].text));
            if(stmtStart && (w=="if" || w=="for" || w=="while" || w=="until" || w=="case" || w=="{")) ++d;
            else if(stmtStart && d>0 && (w=="fi" || w=="done" || w=="esac" || w=="}")) --d;
            else if(d==0 && w=="|") return runSimple(shellWordsRawText(input,words,from,to));
@@ -4005,7 +4072,8 @@ int fresh::Shell::runSegmentWords(const std::string &input,const std::vector<She
                               words[i-1].text=="if" || words[i-1].text=="elif" ||
                               words[i-1].text=="while" || words[i-1].text=="until" ||
                               words[i-1].text=="do" || words[i-1].text=="then" ||
                               words[i-1].text=="else" || words[i-1].text=="!" || words[i-1].text=="{");
                               words[i-1].text=="else" || words[i-1].text=="!" || words[i-1].text=="{" ||
                           endsWithFnParens(words[i-1].text));
            if(atStmtStart && words[i].text=="{") ++depth;
            else if(atStmtStart && words[i].text=="}"){
                if(--depth==0){ closeIdx=i; break; }
@@ -4185,7 +4253,8 @@ void fresh::Shell::collectFunctionDefinitions(const std::string &input,std::vect
                          words[i-1].text=="if" || words[i-1].text=="elif" ||
                          words[i-1].text=="while" || words[i-1].text=="until" ||
                          words[i-1].text=="do" || words[i-1].text=="then" ||
                          words[i-1].text=="else" || words[i-1].text=="!" || words[i-1].text=="{";
                          words[i-1].text=="else" || words[i-1].text=="!" || words[i-1].text=="{" ||
                           endsWithFnParens(words[i-1].text);

        if(depth==0 && atStmtStart){
            std::string name;
@@ -4462,7 +4531,8 @@ int fresh::Shell::parse(const std::string &input,bool applyErrexit){
                        words[k-1].text=="if" || words[k-1].text=="elif" ||
                        words[k-1].text=="while" || words[k-1].text=="until" ||
                        words[k-1].text=="do" || words[k-1].text=="then" ||
                        words[k-1].text=="else" || words[k-1].text=="!" || words[k-1].text=="{");
                        words[k-1].text=="else" || words[k-1].text=="!" || words[k-1].text=="{" ||
                           endsWithFnParens(words[k-1].text));
            if(start && (t=="if" || t=="for" || t=="while" || t=="until" || t=="case" || t=="{"))
                ++d;
            else if(start && d>0 && (t=="fi" || t=="done" || t=="esac" || t=="}"))
@@ -4603,7 +4673,8 @@ int fresh::Shell::parse(const std::string &input,bool applyErrexit){
                           words[i-1].text=="if" || words[i-1].text=="elif" ||
                           words[i-1].text=="while" || words[i-1].text=="until" ||
                           words[i-1].text=="do" || words[i-1].text=="then" ||
                           words[i-1].text=="else" || words[i-1].text=="!" || words[i-1].text=="{");
                           words[i-1].text=="else" || words[i-1].text=="!" || words[i-1].text=="{" ||
                           endsWithFnParens(words[i-1].text));
        if(atStmtStart && (w=="if" || w=="for" || w=="while" || w=="until" || w=="case" || w=="{"))
            ++depth;
        else if(atStmtStart && depth>0 && (w=="fi" || w=="done" || w=="esac" || w=="}"))
+4 −0
Changes for src/shell.h: 4 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -701,6 +701,10 @@ namespace fresh {
        ShellCommand *_lastShellCommand;
        bool _running;
        int _exitCode;
        // exit status of the last "$(...)"/`...` run, -1 if none since the
        // current simple command started (an assignment-only command
        // returns it: "if v=$(cmd)")
        int _lastSubstStatus;
        std::map<int,std::string> _traps;
        std::map<int,struct sigaction> _originalSignalActions;
        bool _runningTraps;