Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # ------------------------------------------------------------------------------
- # -- Editor's Little Helper. :)
- # ------------------------------------------------------------------------------
- # Open and/or search for a set of files and open them in your favourite text
- # editor.
- #
- # Author: Robert Mark Bram
- # v 1.2 - 21/06/2007 1:03PM. Made the script interactive
- # v 1.3 - 26/06/2007 7:46AM. Modified usage comments. Fixed handling of spaces
- # in files names.
- # v 1.4 - 6/07/2007 3:16:51 PM. Modified to protect against invalid indexes
- # being entered by the user.
- # v 1.5 - 8/07/2007 4:31:23 PM. Split openFile function into open file by index
- # or path where each method should be called explicitly. Fixed error where
- # script was opening all by index, assuming paths were indexes!
- # v 1.6 - 8/07/2007 4:37:47 PM. Split printListOfFiles function into two
- # functions, one that would print the index of each file along with the file
- # path, and one that would only print the path. Useful if this command is to
- # be part of a pipe.
- # v 1.7 - 19/11/2007 12:31:44 PM. Included the ability to follow (or not) symbolic
- # links by hooking into the find command's capability for this. By default, do
- # not follow symbolic links.
- # v 1.8 - 29/02/2008 3:23:20 PM. Exclude files matching:
- # grep -v '[.]svn-base$\|zzbuild\|[.]class$\|[.]bak$'
- # v 1.8.1 - 12/05/2008 5:16:51 PM. Added another path for ultra edit.
- # Thursday 6 June 2013, 04:17:59 PM
- # - Fixed second method of opening files in Eclipse.
- # Friday 31 January 2014, 05:22:54 PM
- # - Minor format change to the way I declare functions.
- # Friday 28 February 2014, 06:31:37 PM
- # - Major update that took all day when I should have been working.. but oh well:
- # It was worth it. :)
- # - Modified handling of files so that a single file or whole array can be opened
- # in the editor in one step.
- # - Cleaned up usage function.
- # - Modify argument handling to use processArguments function with getopts.
- # - Update script so that you give choice of editors: vim, ultraedit, eclipse,
- # notepad; no more can you specify editor command by name - you must choose
- # one of these. Otherwise, it is too hard to know how to handle the "x"
- # choice - you don't know if it is a Windows or Cygwin exe so you don't know
- # for sure whether you should process the paths.
- # - Let user change editor from document selection screen.
- # - Add verbose option through the message function, which checks if verbose is
- # on or not.
- # - Double check if examples are OK and still relevant.
- # - Check all exit values to make non-0 cases unique.
- # - Added function comments.
- # Monday 3 March 2014, 03:22:44 PM
- # - Change -L option for following symbolic links to -y instead.
- # - Removed -P option for not following symbolic links and left it as the
- # default option, which can be toggled by -y.
- # - Added -L searchTerm option so that if using less or vim, open files
- # searching for searchTerm.
- # Tuesday 4 March 2014, 06:46:25 PM
- # - Changed usage to output $commandName.
- # - Changed the way we deal with case sensitivity from command line options so that it can be applied more regularly across find and grep commands.
- # - Changed the way we deal with regex from command line options so that we can change find commands properly.
- # - Removed fileNamePattern and am just using filePattern.
- # - Keep arguments to find and grep in separate arrays: findArg grepArg.
- # - Big update to commnts to reflect a separation of argument types: -f, -F and -y to modify the find command; other trailing arguments to modify the grep.
- # - Process all arguments to script in same function. How to handle getopts args and operands at the same time: http://stackoverflow.com/a/21169366/257233
- # - Added -y option as per search.
- # - Added verbose handling and outputAllArgs()
- # - Simplified use of find command in getFilesFromFind() to use an array of args.
- # Tuesday 4 March 2014, 06:56:10 PM
- # - Updated usage comments.
- # Thursday 6 March 2014, 12:29:58 PM
- # - Modified handling of startOfSubjectLine option because it wasn't working. Gawk sees ^ as start of the whole record string, not as start of a new line, and gawk doesn't have \n at the start of each record.. so I have to be a bit more creative and recognise that a record set starts with a line that ends with >>.
- # - Re-added -F option when using less so that if output is less than one screen, it doesn't take over whole screen.
- # - Updated these comments.
- # Wednesday 05 November 2014, 12:04:39 PM
- # - Deal with file/folder names containing space by changing IFS.
- # Monday 05 January 2015, 06:19:22 PM
- # - Added "/target/" to the exclusion string.
- # Sunday 18 January 2015, 02:13:34 PM
- # - Update doc for dependencies.
- # ------------------------------------------------------------------------------
- # -- Dependencies
- # ------------------------------------------------------------------------------
- # Path to UltraEdit to be set in environment variable UEDIT.
- # Path to Eclipse to be set in environment variable ECLIPSE.
- # ------------------------------------------------------------------------------
- # -- Variables for this script.
- # ------------------------------------------------------------------------------
- # Shortcut for the name of this file - for docs.
- commandName=`echo $0 | sed 's|.*/||'`
- # Directory from which we search for files.
- baseDir=.
- # Case insensitive by default - used for FindArg and GrepArg
- caseSensitive=no
- # Follow symbolic links? As per the find command. Defaults to no (-P). Used for FindArg
- symbolic=-P
- # Will the find command be regex or not - used for FindArg
- findArgRegex=no
- # Pattern to use in find command - specificed by FindArg.
- filePattern=*
- # Form used for find command
- findArg=()
- # Form used for grep command
- grepArg=()
- # Absolute path (or command string) to the editor to use when opening up files.
- editor=u
- # Interactive mode: [F]ull, [L]ist, [N]one or [P]artial.
- interactivityMode=P
- # If in partial interactivity, how many files do we have to find in order to
- # trigger interactivity?
- minFilesInteractive=2
- # Did we actually have to search for files? If no, then all trailing args to
- # this script were valid relative paths from base dir or valid absolute paths.
- # Needed to work out what to do in partial interactivity mode.
- searchPerformed=N
- # Array of files given from the command line
- arrayOfFilesFromCommandLine=()
- # Message to display when need to output editor choice in an echo.
- editorChoiceMessage='EDITOR can be one of [e]clipse, [u]ltraedit, [l]ess, n[o]tepad or [v]im.'
- # Should we be verbose?
- verbose=no
- # If using the -L option, store search term here.
- searchTermLess=
- # Files to exclude in search in FIND command.
- excludeParams=(-not -iwholename '*.svn*' -not -iwholename '*.bak*' -not -iwholename '*.class*' -not -ipath '*/target/*')
- # ------------------------------------------------------------------------------
- # -- Common functions for this script.
- # ------------------------------------------------------------------------------
- # === FUNCTION ===============================================================
- # DESCRIPTION: Output message if verbose is on
- # PARAMETERS: message to be printed
- # RETURNS: -
- # ==============================================================================
- function message() {
- if [ "$verbose" == "yes" ] ; then
- echo -e "${1}"
- fi
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Output help and usage message
- # PARAMETERS: error message to be printed
- # RETURNS: -
- # ==============================================================================
- function usage() {
- errMessage=
- if [ "$#" -gt 0 ] ; then
- errMessage=$1
- else
- errMessage=HELP
- fi
- less << STOP_HELP
- $errMessage
- Search for a set of files and open them in your favourite text editor
- Usage: $commandName [Miscellaneous Arguments] [FindArg] [GrepArg ... ]
- Works in three parts
- - FindArg is used in a find command to create the superset of files.
- - GrepArg is used to filter the superset to make a subset - one for each
- GrepArg supplied
- - GrepArg (trailing args) could also be actual paths to existing files,
- in which case no grepping is actually needed.
- --- FindArg
- Used to form find command to construct superset of files.
- Must use one of the below forms to specify file type for the search.
- -f filePattern Search pattern for file names. Argument is as per
- "find . -name FILE_NAME_PATTERN". Not regex.
- -F filePattern Search pattern for file names. Argument is as per
- "find . -regex FILE_NAME_PATTERN". IS A REGEX.
- -y type File pattern based on file extension using a type
- shortcut from below.
- Available type shortcuts:
- a *.js files - Javascript.
- b *.php files.
- c *.css files.
- d *.sh files.
- e Everything except things defined here:
- ${excludeParams[@]}
- E Everything including bak and svn and class
- h *.html or *.htm files.
- i *.idx files.
- j *.java files.
- j *.sh files - shell files.
- p *.jsp|jsph files.
- r *.properties files.
- s *.sql files.
- t *.txt files.
- x *.xml files.
- z All Java related files
- *.java files.
- *.jsp|jsph files.
- *.properties files.
- --- GrepArg
- A series of optional regular expressions.
- --- Miscellaneous Arguments
- [-d directory] Use directory other than default - which is the current dir.
- [-e editor] Specify an editor to use.
- $editorChoiceMessage
- [-h|-help] Displays this message and exits.
- [-i option] Define mode of interactivity. Defaults to Partial.
- [F]ull: display lists of files and ask user what ones to open.
- [L]ist: lists files only. No other form of interaction.
- [N]one: do not display list of files or ask the user anything:
- automatically open all files found.
- [P]artial: can act as Full or None as per below.
- - act as None if number of files found <= MIN_FILES_INTERACTIVE
- - act as None if all trailing args were valid relative
- paths to files from DIRECTORY or valid absolute paths.
- [-L searchTerm] If using -e l|v, this option will ensure that when the file is
- opened in less or vim, searchTerm will be searched for.
- [-m min_files_interactive]
- Set the minimum number of files that should be found in order
- to trigger interaction when in Partial interactivity mode.
- Defaults to 2.
- [-s] Case sensitive.
- [-v] Verbose output.
- [-y] Follow symbolic links (as per find command).
- Default is never follow symbolic links.
- ==========================
- General process for searching for files.
- 1) Find superset of files from target directory with the find command.
- - Can apply arguments to modify find command file name pattern.
- - Can apply arguments to modify target directory.
- 2) Apply regular expressions to superset of files to get selection set.
- - Can use one or more regular expressions via trailing arguments
- to this command.
- - By default, ignores a common set of files through this snippet sent to find:
- ${excludeParams[@]}
- 3) Ask what files you wish to open in the editor.
- - Can apply argument to turn off interactive mode - all files get
- opened.
- - Can apply argument to set your own editor.
- ==========================
- Examples.
- $0 -i l "commandbean.java$"
- List all files from the current directory down whose relative path
- (including file name) ends with "commandbean.java" - case
- insensitive. Here it is effectievly doing:
- find . -name "*" | grep -i "commandbean.java$"
- $0 -i l -f "*.java" commandbean
- $0 -i l -f ".*commandbean.*\\.java"
- $0 -i l -f ".*commandbean.*.java"
- List all files from the current directory down whose file name
- ends with ".java" and whose relative path - including file name -
- contains "commandbean" - case insensitive. Here it is effectievly
- doing:
- find . -name "*.java" | grep -i "commandbean"
- $0 "status.*/.*java$"
- $0 -f "*.java" "status.*/"
- Ask me to open files from list of Java source files in a package
- that includes the token "status" somewhere in it -- assuming there
- are more than 1.
- $0 ./some/path/to/MyClass1.java \\
- ./some/path/to/MyClass2.java \\
- ./some/path/to/MyClass3.java \\
- Open up the files specified in UltraEdit.
- $0 ./some/path/to/MyClass1.java ".*.properties$"
- Ask me to open files from list of a specific Java source file and
- all properties file that are found in /base/dir -- assuming the
- list has more than 1 result.
- $0 ./some/path/to/MyClass1.java -e v -L "This is a comment"
- Open MyClass1.java in vim and automatically search for the string "This is a
- comment"
- Things that should show the same results:
- - Testing find args for files in ./libs/ctags58/*. Note: -regex in find covers file path and name.
- cd ~ ; find . -type f -regex ".*libs.*ctags58.*"
- cd ~ ; find . -type f -regex ".*libs.*ctags58.*" | wc -l
- u -i l -F ".*libs.*ctags58.*" -s
- u -i l -F ".*libs.*ctAGS58.*"
- - Testing find args for files va*.vim. Note: -name in find covers file name only.
- cd ~ ; find . -type f -name "va*.vim"
- u -i l -d ~ -f "va*.vim" -s
- u -i l -d ~ -f "VA*.Vim"
- - Testing find args using type
- cd ~/nd ; find . -type f -name "*.html" -o -name "*.htm"
- u -i l -d ~/nd -y h
- - Testing find args using type and regex and case sensitivity off
- ./js/DO_NOT_UPLOAD_royalSliderSrc/templates/ajax-sliders/simple-slider.html
- cd ~/nd ; find . -type f -iregex ".*TEMPLATES.*slider.html"
- u -i l -d ~/nd -y h ".*TEMPLATES.*slider.html"
- - Testing grep args
- cd ~ ; find . -type f -name "va*.vim" -iregex ".*ator.*"
- u -i l -d ~ -f "va*.vim" ".*ator.*" -s
- u -i l -d ~ "va.*ator.*.*vim" -s
- - Testing gep args with or conditions to target file names, NOT paths
- cd ~ ; find . -type f -name "cof*.vim" -o -name "caf*.vim"
- u -i l -d ~ -f "*.vim" "/cof.*\.vim" "/caf.*\.vim"
- - Testing gep args with or conditions to target file names AND paths
- cd ~ ; find . -type f -iregex ".*COF.*.vim" -o -iregex ".*caf.*.vim"
- u -i l -d ~ -f "*.vim" "COF.*\.vim" "caf.*\.vim"
- - Everything - should be the same number of files
- cd ~ ; find . -type f -not -iwholename "*.svn*" -not -iwholename "*.bak*" -not -iwholename "*.class*" | wc -l
- u -i l -d ~ | wc -l
- - bak or not to bak - should be the same number of files
- - Set up test dir.
- rm -rf /tmp/temptest
- mkdir /tmp/temptest
- cd /tmp/temptest
- touch firstFile.txt
- touch firstFile.bak
- - Should show the same result
- find . -name "*.txt"
- u -i l -d /tmp/temptest -y t
- - Should show the same result
- find . -name "*.bak"
- u -i l -d /tmp/temptest -y E bak
- STOP_HELP
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Process all arguments to script. How to handle getopts args
- # and operands at the same time:
- # http://stackoverflow.com/a/21169366/257233
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- function processArguments() {
- # Loop to handle all parameters
- non_option_parameters=()
- while true; do
- # Process single letter args.
- while getopts "$OPTIONS" option; do
- if ! processSingleLetterArguments "$option"; then exit 9; fi
- done
- if ((OPTIND > $#)); then break; fi
- non_option_parameters+=(${!OPTIND})
- # Handle operand arg - arrayOfFilesFromCommandLine not handled by getopts
- arrayOfFilesFromCommandLine+=("${!OPTIND}")
- ((OPTIND++))
- done
- # ---------------------------------------------------------------------------
- # Post argument processing - logic that must be applied once we know all args.
- # ---------------------------------------------------------------------------
- # Figure out find command.
- findForm=
- if [ "$caseSensitive" = "yes" -a "$findArgRegex" = "yes" ] ; then
- findForm="-regex"
- elif [ "$caseSensitive" = "yes" -a "$findArgRegex" = "no" ] ; then
- findForm="-name"
- elif [ "$caseSensitive" = "no" -a "$findArgRegex" = "yes" ] ; then
- findForm="-iregex"
- elif [ "$caseSensitive" = "no" -a "$findArgRegex" = "no" ] ; then
- findForm="-iname"
- else
- usage "Am in impossible condition. Exit."
- exit 44
- fi
- findArg=("${symbolic}" '.' "${excludeParams[@]}" '-type' 'f' "$findForm" "$filePattern")
- # Figure out grep command.
- if [ "$caseSensitive" = "yes" ] ; then
- grepArg=( '' )
- else
- grepArg=( '-i' )
- fi
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Process single letter args via getopts
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- OPTIONS=":bd:e:f:F:hi:L:m:svy:"
- function processSingleLetterArguments() {
- case "$1" in
- b ) symbolic="-L";;
- d ) baseDir="$OPTARG";;
- e ) validateEditorChoice "$OPTARG";;
- f ) filePattern="$OPTARG";;
- F ) filePattern="$OPTARG";
- findArgRegex=yes;;
- h ) usage; exit 0;;
- i ) setUpInteractivity "$OPTARG";;
- L ) searchTermLess="$OPTARG";;
- m ) minFilesInteractive="$OPTARG";;
- s ) caseSensitive=yes;;
- v ) verbose=yes;;
- y ) processFileType "$OPTARG";;
- \?) usage "*** Invalid option: -$OPTARG ***"; exit 10;;
- :) usage "*** Option -$OPTARG requires an argument. ***"; exit 11;;
- esac
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Process choice of what type of file to look through?
- # Analyses filePattern and filePatternType variables.
- # Note: code shared by search.sh and u.sh. So if you modify one,
- # make the same change to the other Rob!
- # PARAMETERS: Potential filePattern
- # RETURNS: -
- # ==============================================================================
- function processFileType() {
- case "${1}" in
- a) filePattern='*.js';;
- b) filePattern='*.php';;
- c) filePattern='*.css';;
- d) filePattern='*.sh';;
- e) filePattern='*.*';;
- E) filePattern='*.*';
- excludeParams=();;
- h) findArgRegex=yes;
- filePattern='.*.htm[l]?';;
- i) filePattern='*.idx';;
- j) filePattern='*.java';;
- l) filePattern='*.sh';;
- p) findArgRegex=yes;
- filePattern='.*[.]jsp[h]?';;
- r) filePattern='*.properties';;
- s) filePattern='*.sql';;
- t) filePattern='*.txt';;
- x) filePattern='*.xml';;
- z) findArgRegex=yes;
- filePattern='.*[.]\(jsp[h]?\|java\|properties\)';;
- *) usage "*** Unknown -type: $filePatternType. ***"; exit 3;;
- esac
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Process command line arg governing interactivity.
- # PARAMETERS: interactivity flag
- # RETURNS: -
- # ==============================================================================
- function setUpInteractivity() {
- case "$1" in
- "F" | "f" ) interactivityMode="F";;
- "L" | "l" ) interactivityMode="L";;
- "N" | "n" ) interactivityMode="N";;
- "P" | "p" ) interactivityMode="P";;
- * ) usage "Invalid option for -i. [F]ull, [L]imited or [N]one."; exit 2;;
- esac
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Process command line arg governing minFilesInteractive.
- # PARAMETERS: minFilesInteractive flag
- # RETURNS: -
- # ==============================================================================
- function setUpMinFilesInteractive() {
- if [ -n "`echo "$1" | grep -E -e '^[0-9]+$'`" ]
- then
- minFilesInteractive="$1"
- else
- usage "Invalid option for -m; not a number."
- exit 3
- fi
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Work out what editor to use if the user didn't specify one.
- # Set the path to that editor in a script variable, "editor".
- # PARAMETERS: editor flag
- # RETURNS: -
- # ==============================================================================
- function validateEditorChoice() {
- case "$1" in
- "e" | "E" ) editor="e";;
- "u" | "U" ) editor="u";;
- "l" | "L" ) editor="l";;
- "o" | "O" ) editor="o";;
- "v" | "V" ) editor="v";;
- * ) usage "Invalid option for -e. $editorChoiceMessage"; exit 4;;
- esac
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Output all the arguments we have if verbose is turned on.
- # Outputs most variables in script.
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- function outputAllArgs() {
- if [ "$verbose" == "yes" ] ; then
- echo "--- List of args -----------------------------------------"
- echo "Arg arrayOfFilesFromCommandLine: [${arrayOfFilesFromCommandLine[@]}]"
- echo "Arg baseDir: [${baseDir}]"
- echo "Arg caseSensitive: [${caseSensitive}]"
- echo "Arg commandName: [${commandName}]"
- echo "Arg editor: [${editor}]"
- echo "Arg editorChoiceMessage: [${editorChoiceMessage}]"
- echo "Arg excludeParams: [${excludeParams[@]}]"
- echo "Arg filePattern: [${filePattern}]"
- echo "Arg findArg: [${findArg[@]}]"
- echo "Arg findArgRegex: [${findArgRegex}]"
- echo "Arg grepArg: [${grepArg[@]}]"
- echo "Arg interactivityMode: [${interactivityMode}]"
- echo "Arg minFilesInteractive: [${minFilesInteractive}]"
- echo "Arg searchPerformed: [${searchPerformed}]"
- echo "Arg searchTermLess: [${searchTermLess}]"
- echo "Arg symbolic: [${symbolic}]"
- echo "Arg verbose: [${verbose}]"
- echo "----------------------------------------------------------"
- fi
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Open files that have been selected - filesToOpen must contain
- # a list of space separated indexes to the associative array of
- # files, fileSet.
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- function openSelectedFiles() {
- # Create new array out of selected files.
- newFileSet=()
- for nextIndex in $filesToOpen ; do
- case "$nextIndex" in
- *[!0-9]*|"" ) echo "Not a valid index: $nextIndex";;
- * ) newFileSet+=("${fileSet[$nextIndex]}");;
- esac # Allows ranges of characters in [square brackets],
- done
- unset fileSet
- fileSet=( "${newFileSet[@]}" )
- openAllFiles
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Open all files in the array of files, fileSet. This must be
- # the ONLY method that actually opens files.
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- function openAllFiles() {
- if [ ${#fileSet[@]} -eq 0 ] ; then
- echo "No files to open."
- exit 5
- fi
- case "$editor" in
- e ) convertFileSetToWindowsPaths # Eclipse
- $ECLIPSE --launcher.openFile \
- "${fileSet[@]}" & ;;
- l ) if [ -z "$searchTermLess" ] ; then
- less "${fileSet[@]}" # less
- else
- less -I -p "${searchTermLess}" "${fileSet[@]}"
- fi
- ;;
- o ) # notepad
- for index in "${!fileSet[@]}" ; do
- notepad "${fileSet[$index]}" &
- done ;;
- u ) convertFileSetToWindowsPaths # UltraEdit
- "$UEDIT" "${fileSet[@]}" & ;;
- v ) if [ -z "$searchTermLess" ] ; then
- vim ${fileSet[@]} # vim
- else
- echo ######################################### search for searchTermLess: $searchTermLess
- vim +/"${searchTermLess}" ${fileSet[@]}
- fi
- ;;
- * ) usage "Unknown editor option [$editor]. How did you even get here?" ; exit 6;;
- esac
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Convert array of paths in Cygwin format to Windows format.
- # Modified fileSet in place.
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- function convertFileSetToWindowsPaths() {
- index=0
- while [ "${index}" -lt "${#fileSet[@]}" ]
- do
- # echo File [${index}]: ${fileSet[$index]}
- fileSet[$index]=`cygpath -w -a "${fileSet[$index]}"`
- let "index++"
- done
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Print list of files in the set - printing index for each entry.
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- function printListOfFilesWithIndex() {
- index=0
- while [ "${index}" -lt "${#fileSet[@]}" ]
- do
- printf "File %*d: %s\n" 2 ${index} "${fileSet[$index]}"
- let "index++"
- done
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Print list of files in the set - without an index for each entry.
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- function printListOfFilesWithoutIndex() {
- index=0
- while [ "${index}" -lt "${#fileSet[@]}" ]
- do
- echo "${fileSet[$index]}"
- let "index++"
- done
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Find files from the file name arguments to this script.
- # Each argument could be a
- # - valid relative path to a file from base dir.
- # - valid absolute path to a file.
- # - regular expression to be used to grep over results of a find.
- # Fill up a variable called fileSet with the results.
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- function getFilesFromFindAndGrep() {
- fileIndex=0
- # Go through file arguments.
- for index in ${!arrayOfFilesFromCommandLine[@]} ; do
- # If the argument is a file path that exists, put it in the file set
- if [ -f "${arrayOfFilesFromCommandLine[$index]}" ] ; then
- # echo File path: "${arrayOfFilesFromCommandLine[$index]}"
- fileSet[$fileIndex]="${arrayOfFilesFromCommandLine[$index]}"
- let "fileIndex++"
- else
- # Otherwise, treat argument as a regular expression to modify superset of
- # files - which is itself the result of a find command.
- # We are searching..
- searchPerformed=Y
- message "RUNNING find ${findArg[@]} | grep ${grepArg[@]} ${arrayOfFilesFromCommandLine[$index]}"
- files=`find "${findArg[@]}" | grep ${grepArg[@]} "${arrayOfFilesFromCommandLine[$index]}"`
- # Put each file we found into file set.
- for file in $files ; do
- # echo File from expressio: "$file"
- fileSet[$fileIndex]="$file"
- let "fileIndex++"
- done
- fi
- done
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Find files using only a find - no grep, no file paths.
- # Fill up a variable called fileSet with the results.
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- function getFilesFromFind() {
- # No trailing args - we are searching..
- searchPerformed=Y
- message "RUNNING find ${findArg[*]}"
- files=`find "${findArg[@]}"`
- # Put each file we found into file set.
- for file in $files ; do
- # echo File from expression "$file"
- fileSet[$fileIndex]="$file"
- let "fileIndex++"
- done
- }
- # === FUNCTION ===============================================================
- # DESCRIPTION: Display list of files and ask user which ones to open. Puts
- # their answer into variable called fileToOpen.
- # PARAMETERS: -
- # RETURNS: -
- # ==============================================================================
- function askUserWhatFilesToOpen() {
- printListOfFilesWithIndex
- echo ----
- echo Specify files to open. [A]ll, [N]one or [x y z] space separated indexes.
- echo Can also override editor choice. $editorChoiceMessage
- read filesToOpen
- # echo We will open these: ${filesToOpen}
- newFilesToOpen=
- openNoFiles=no
- openAllFiles=no
- # Reset separator to what it was.
- IFS="$oldIFS"
- for word in $filesToOpen ; do
- case "${word}" in
- "e" | "u" | "l" | "o" | "v" | "E" | "U" | "L" | "O" | "V")
- editor=${word}
- message "Changing editor to ${word}";;
- "n" | "N") openNoFiles="yes";;
- "a" | "A") openAllFiles="yes";;
- *[!0-9]*|"" ) echo "Not a valid index: $word";;
- * ) newFilesToOpen+=" ${word}";;
- esac
- done
- if [ "$openNoFiles" = "yes" ] ; then
- message "You chose to open no files. Done."
- exit 0
- fi
- if [ "$openAllFiles" = "yes" ] ; then
- message "You chose to open all files."
- openAllFiles
- exit 0
- fi
- if [ -z "$newFilesToOpen" ] ; then
- message "No files to open (or all indexes were invalid)."
- exit 7
- else
- message "Opening files based on selected indexes: $newFilesToOpen"
- filesToOpen="$newFilesToOpen"
- openSelectedFiles
- fi
- }
- # ------------------------------------------------------------------------------
- # -- Script Logic
- # ------------------------------------------------------------------------------
- # Process all the arguments.
- processArguments "$@"
- cd "$baseDir"
- outputAllArgs
- # Make delimiter equal to whatever newline char we are using now
- oldIFS=$IFS
- # MUST keep this aligned to edge like this to correctly interpret new line.
- IFS="
- "
- if [ "${#arrayOfFilesFromCommandLine[@]}" -eq 0 ] ; then
- message "Get files from file pattern."
- getFilesFromFind
- else
- message "Get files from command line."
- getFilesFromFindAndGrep
- fi
- if [ ${#fileSet[@]} -eq 0 ]
- then
- echo No files found.
- exit 0
- fi
- # Just list the files?
- if [ "$interactivityMode" = "L" ]
- then
- printListOfFilesWithoutIndex
- # Open all of the files without asking? Interactive mode is [N]one.
- elif [ "$interactivityMode" = "N" ] ; then
- openAllFiles
- # Interactive mode is [P]Artial.
- # Ask the user what files to open if no search was performed or if number of
- # files found was less than min required to trigger interactivity.
- elif [ "$interactivityMode" = "P" ] ; then
- if [ "${#fileSet[@]}" -lt "$minFilesInteractive" -o "$searchPerformed" = "N" ]
- then
- openAllFiles
- else
- askUserWhatFilesToOpen
- fi
- # Interactive mode is [F]ull.
- # Ask the user what files to open if we are in interactive mode.
- else
- askUserWhatFilesToOpen
- fi
- # echo Done.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement