Home > Software design >  Get specific parameters from all functions in javascript file
Get specific parameters from all functions in javascript file

Time:01-20

Sample input file

function getRepoReviewers(gitHost, repoURL) {
     return {
          method: 'GET', headers: "",
          url: `v1/api/code/${gitHost}/reviewers/${repoURL}`
     }
}

function getRepoBranches(gitHost, repoURL) {
     return {
          method: 'GET', headers: "",
          url: `v1/api/code/${gitHost}/branches/${repoURL}`
     }
}

Expected output to get

GET, v1/api/code/${gitHost}/reviewers/${repoURL}
GET, v1/api/code/${gitHost}/branches/${repoURL}

I tried with help of below shell script to read line by line using below regex but not able to get the desired result.

for entry in "$1"/*
do
  var=$(tr '´' "'" < $entry);
  printf "%s" "$var" > file.txt;
  list1=$(grep -o "[^']*v1[^']*" file.txt);
  list2=$(grep -o "[^']*v2[^']*" file.txt);
  echo "$list1" >> api_endpoints_bat_api.csv
  echo >> api_endpoints_bat_api.csv
  echo "$list2" >> api_endpoints_bat_api.csv
  echo >> api_endpoints_bat_api.csv
done

CodePudding user response:

Here is a one-liner using pipes:

cat test.js |\
 egrep 'method:|url:' |\
 perl -pe 'BEGIN{undef $/} s/\s url:/ url:/g' |\
 grep '.' |\
 tr '`' "'" |\
 perl -pe "s/.*method: '([^']*)'.*url: '([^']*).*/\1,\2/"

Output with your file:

GET,v1/api/code/${gitHost}/reviewers/${repoURL}
GET,v1/api/code/${gitHost}/branches/${repoURL}

Explanation:

  • egrep: use only lines of interest
  • 1st perl: join the url line with previous line, the BEGIN{undef $/} tells perl to be in multi-line mode
  • grep: use only non-empty lines
  • tr: change back quote to '
  • 2nd perl: capture and use only method and url

BTW, if you want to feed this to a .csv file you should omit the space after the comma.

  • Related