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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
#!/bin/sh
#------------------------------------------------------------------------------
# =========                 |
# \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
#  \\    /   O peration     | Website:  https://openfoam.org
#   \\  /    A nd           | Copyright (C) 2024-2026 OpenFOAM Foundation
#    \\/     M anipulation  |
#------------------------------------------------------------------------------
# License
#     This file is part of OpenFOAM.
#
#     OpenFOAM is free software: you can redistribute it and/or modify it
#     under the terms of the GNU General Public License as published by
#     the Free Software Foundation, either version 3 of the License, or
#     (at your option) any later version.
#
#     OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
#     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
#     for more details.
#
#     You should have received a copy of the GNU General Public License
#     along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.
#
# Script
#     foamFind
#
# Description
#     Finds one or more files in OpenFOAM and optionally processes the contents
#     by printing the file or lines matching a search string
#
#------------------------------------------------------------------------------
usage () {
    cat <<USAGE

Usage: ${0##*/} [OPTIONS] <filename>
options:
  -a | -applications     search for the file from the \$FOAM_APP directory
  -c | -coded <file>     insert entries to codeInclude, codeOptions and codeLibs
                         blocks of coded input in the specified file
  -C                     only list .C files
  -d | -dir <dir>        specify search directory
  -e | -edit             open the file in a file editor, see below for info
  -f | -files            find wmake 'files' file associated with searched file
  -h | -help             help
  -H                     only list .H files
  -i | -isearch <string> searches files for a <string>, case insensitive
  -l | -lnInclude        find 'lnInclude' directory for searched file, print
                         the corresponding '-I' flag and '-l' library for an
                         'options' file
  -m | -modules          search for the file from the \$FOAM_MODULES directory
  -n | -numbers          print line numbers with file output
  -o | -options          find wmake 'options' file associated with searched file
  -p | -print            print the file(s)
  -s | -search <string>  searches files for a <string>, case sensitive
  -t | -tutorials        search for the file from the \$FOAM_TUTORIALS directory

Finds one or more files in OpenFOAM and optionally processes the contents by:
+ printing the file(s) ('-print' option);
+ printing lines within the file matching a search string ('-search' option);
+ opening a single (only) file in a text editor ('-edit' option).

The '-edit' option required the user to specify their choice of text editor by
setting the EDITOR environment variable. For example, to set the 'gedit' editor,
they could add to their \$HOME/.bashrc file, the line:

export EDITOR=gedit

With source code files, can locate the 'files' and 'options' files associated
with their compilation using 'wmake'.

By default, files are searched from the src (\$FOAM_SRC) directory.
Alternatively the '-dir' option allows the user to specify the search directory
The '-applications', '-modules' and '-tutorials' options specifically set the
search path to the \$FOAM_APP, \$FOAM_MODULES and \$FOAM_TUTORIALS directories,
respectively.

Examples:
    foamFind -print wallHeatFlux.C | less
    + click space bar to scroll down
    + enter line number (after ":") to jump to line
    + enter "/text" to search for "text" (or any other string)

    foamFind -applications -isearch "momentumtransport" -options fluid.C
    foamFind -numbers -search laminar BirdCarreau.C

USAGE
}

error() {
    exec 1>&2
    while [ "$#" -ge 1 ]; do printf "%s" "$1"; shift; done
    printf "\n"
    usage
    exit 1
}

findWmakeFiles () {
    _file="$1" ; shift
    _wmakeFiles="$*"

    # Check if file is source code
    ! file -b "$_file" | grep -Eq "C.*source" && \
        "'-$_filename' invalid, file is not source code" >&2 && \
        return 1

    _files=""
    while true
    do
        _oldFile="$_file"
        _file="${_file%/*}"

        # cannot contract the path further
        [ "$_oldFile" = "$_file" ] && break

        # search for 'files' and/or 'options'
        [ -d "$_file" ] && \
            for _w in $_wmakeFiles
            do
                _files="$(echo "$_files" \
                       "$(find "$_file" -name "$_w")" | xargs)"
            done

        [ "$_files" ] && break
    done

    ! [ "$_files" ] && \
        error "no '$_filename' file found for '-files' or '-options'" >&2 && \
        return 1

    echo "$_files"
    return 0
}

# Prints lnInclude entry to terminal and optionally write codeInclude and
# codeOptions entries in coded input to a file
writeCoded () {
    # The lnInclude file
    _lnInclude="$1"
    _codeOptions="-I\$(LIB_SRC)/${_lnInclude##"$FOAM_SRC/"}"

    # The -I option sometimes sources files in $FOAM_MODULES
    echo "$_lnInclude" | grep -q "$FOAM_MODULES" && \
        _codeOptions="-I\$(FOAM_MODULES)/${_lnInclude##"$FOAM_MODULES/"}"

    # Optional arguments for codeInclude, codeOptions and codeLibs entries
    _file="$2"
    _codeInclude="$3"
    _codeLibs="$(awk -F/ '/LIB =/ {gsub("lib", "-l", $NF); print $NF}' \
              "$_lnInclude/../Make/files" 2>/dev/null)"

    ! [ "$_file" ] && \
        printf "\nDirectory: %s\n" "$_lnInclude" && \
        printf "options entry: %s\n" "$_codeOptions" && \
        printf "libs entry: %s\n" "$_codeLibs" && \
        return 0

    for _b in codeInclude codeOptions codeLibs
    do
        addToCoded "$_file" "$_b" "$(eval echo "\$_$_b")"
    done
}

addToCoded () {
    _file="$1"
    _block="$2"
    _entry="$3"

    # Do not add core OpenFOAM library
    echo "$_entry" | grep -q OpenFOAM && \
        echo "Entry for $_block for the core OpenFOAM library " \
             "is not required" && \
        return 0

    # Expression to match block with name (preceded by optional spaces)
    _match="/^[\t ]*$_block/,/#};/"

    # Check block is correct, number of lines must be >= 3
    _nLines="$(awk "$_match {i++} END {print i}" "$_file")"
    ! [ "$_nLines" -ge "3" ] 2> /dev/null && \
        echo "$_block block in $_file does not exist" \
             "or has incorrect syntax, not adding an entry" && \
        return 0

    # Check block already contains the entry
    awk "$_match {print}" "$_file" | grep -q -- "$_entry" && \
        echo "Entry already exists in $_block block in $_file, ignoring" && \
        return 0

    # Add entry to block
    echo "Adding to $_block in $_file: $_entry"
    _line="$(awk "$_match {i=NR} END {print i}" "$_file")"
    _indent="$(grep "^[\t ]*$_block" "$_file" | sed 's/\(^[\t ]*\).*/\1/')    "

    _tmpfile="$(mktemp "/tmp/${0##*/}.XXXXXX")"
    awk -v n="$_line" -v e="$_indent$_entry" \
        'NR == n {print e} {print}' "$_file" > "$_tmpfile"
    mv "$_tmpfile" "$_file"
}

nParams () {
    [ "$1" ] || return 1

    echo "$1" | xargs | awk -F' ' '{print NF}'
    return 0
}

selectFile () {
    _filename="$1"; shift
    _files="$*"
    _nFiles="$(nParams "$_files")"

    # Return file if only one
    [ "$_nFiles" -eq 1 ] && echo "$_files" && return 0

    printf "Multiple files" >&2
    [ "$_filename" ] && printf " with name '%s'" "$_filename" >&2
    printf " found:\n" >&2

    _i=1
    for _f in $_files
    do
        printf "%i) %s\n" "$_i" "$_f" >&2
        _i=$((_i + 1))
    done
    printf "Type ENTER to select all, 'l' to list files only or " >&2
    printf "enter file number (1-%s) for specific file: " \
           "$_nFiles" >&2

    read -r _nFile

    # Enter nothing
    [ -z "$_nFile" ] && echo "$_files" && return 0

    # List files only
    echo "$_nFile" | grep -q "^[lL]$" && printf "\n%s\n\n" "$_files" >&2 && return 0

    # Check incorrect number
    ! [ "$_nFile" -eq "$_nFile" ] 2>/dev/null && \
        echo "\"$_nFile\" is not a number" >&2 && \
        return 1
    { [ "$_nFile" -lt 1 ] || [ "$_nFile" -gt "$_nFiles" ] ; } && \
        echo "\"$_nFile\" is not a number between 1 and $_nFiles" >&2 && \
        return 1

    # Enter number corresponding to file
    # shellcheck disable=SC2086
    echo $_files | awk -v n="$_nFile" '{print $n}'
    return 0
}

setFile () {
    _files="$1"
    _n="$2"
    echo "$_files" | xargs -n 1 | awk -v n="${_n}" 'NR==n'
}

isSrcDir () {
    echo "$1" | grep -qE "^($FOAM_SRC|$FOAM_APP)"
}

listFiles () {
    _dir="$1"
    _filename="$2"
    _search="$3"
    _ins=""

    [ "$4" = "on" ] && _ins="i"

    # Specify code files if _dir is in $FOAM_SRC or $FOAM_APP
    _name="*"
    isSrcDir "$dir" && _name="*.$FILE_EXTS"
    [ "$_filename" ] && _name="$_filename"

    [ "$_search" ] && \
        find "$_dir" -name "$_name" \
            ! '(' -name '*gz' -or -name '*stl' -or -name '*obj' ')' \
            -type f -print0 | \
            xargs -0 grep -l$_ins "$_search" && \
        return 0

    # Remove "\n"
    find "$dir" -name "$filename" -type f -print0 | xargs -0
}

grepFile () {
    _string="$1"
    _file="$2"
    _ins=""
    [ "$3" = "on" ] && _ins="i"
    _arg="$4"

    # use $_arg for different cases: test, and with and without line numbers
    case "$_arg" in
        test)
            grep -q"$_ins" "$_string" "$_file"
            ;;
        numbers)
            grep -hn"$_ins" "$_string" "$_file" | \
                awk '{
                         split($0,f,":");
                         sub(/^([^:]+:)/,"",$0);
                         printf "%6i  %s\n", f[1], $0
                     }'
            ;;
        *)
            grep -h"$_ins" "$_string" "$_file"
            ;;
    esac
}

dirError () {
    cat<<EOF
Search directory specified with more than one option from '-applications',
'-dir', '-modules' and '-tutorials'. Please specify only one of these options.
EOF
}

editConfigError () {
    cat<<EOF
The '-edit' option requires the user to specify their chosen text editor using
the EDITOR environment variable. For example, to set the 'gedit' editor, they
could add to their \$HOME/.bashrc file, the line:

export EDITOR=gedit

EOF
}

searchError () {
    cat<<EOF
The '-search' and '-isearch' options are both specified.
Please specify only one of these options, either '-isearch' for a
case-insensitive search or '-search' for case-sensitive.
EOF
}

optionsError () {
    cat<<EOF
Two or more of the '-search/-isearch', '-print' and '-edit' options are
specified. Please specify only one of these options, either '-search/-isearch'
to print lines of files(s) matching an expression, or '-print' or '-edit' to
view the entire file(s).
EOF
}

codedError () {
    cat<<EOF
The file argument for for '-coded' option must be a file with placeholders
for coded file input, e.g. a coded function object, containing a codeInclude,
codeOptions and/or codeLibs block
EOF
}

dir=""
print=""
edit=""
wmakeFiles=""
search=""
insensitive=""
numbers=""
filename=""
codedFile=""
FILE_EXTS='[CHL]'

while [ "$#" -gt 0 ]
do
   case "$1" in
   -a | -applications)
       [ "$dir" ] && error "$(dirError)"
       dir="$FOAM_APP"
       shift
       ;;
   -c | -coded)
       [ "$#" -ge 2 ] || error "'$1' option requires an argument"
       [ -f "$2" ] || error "'$2' argument to '-coded' option is not a file"
       ! grep -Eq "code(Include|Options|Libs)" "$2" && error "$(codedError)"
       codedFile="$2"
       shift 2
       ;;
   -C)
       [ "$FILE_EXTS" = '[H]' ] &&  \
           error "'$1' option cannot be used with '-H'"
       FILE_EXTS='[C]'
       shift 1
       ;;
   -d | -dir)
       [ "$dir" ] && error "$(dirError)"
       [ "$#" -ge 2 ] || error "'$1' option requires an argument"
       [ -d "$2" ] || error "'$2' argument to '-dir' option is not a directory"
       # shellcheck disable=SC2164
       dir="$(cd "$2"; pwd)"
       # Check $dir is in OpenFOAM
       ! echo "$dir" | grep -q "^$WM_PROJECT_DIR" && \
           error "Specified directory '$dir' is not in OpenFOAM installation"
       shift 2
       ;;
   -e | -edit)
       { [ "$insensitive" ] || [ "$print" ]; } && error "$(optionsError)"
       [ "$EDITOR" ] || error "$(editConfigError)"
       edit="$(which "$EDITOR")"
       shift
       ;;
   -f | -files)
       wmakeFiles="$wmakeFiles files"
       shift
       ;;
   -h | -help)
       usage
       exit
       ;;
   -H)
       [ "$FILE_EXTS" = '[C]' ] &&  \
           error "'$1' option cannot be used with '-C'"
       FILE_EXTS='[H]'
       shift 1
       ;;
   -i | -isearch)
       [ "$#" -ge 2 ] || error "'$1' option requires an argument"
       [ "$insensitive" ] && error "$(searchError)"
       { [ "$print" ] || [ "$edit" ]; } && error "$(optionsError)"
       search="$2"
       insensitive=on
       shift 2
       ;;
   -l | -lnInclude)
       wmakeFiles="$wmakeFiles lnInclude"
       shift
       ;;
   -m | -modules)
       [ "$dir" ] && error "$(dirError)"
       dir="$FOAM_MODULES"
       shift
       ;;
   -n | -numbers)
       numbers="numbers" # flag for line numbers in cat or grep
       shift
       ;;
   -o | -options)
       wmakeFiles="$wmakeFiles options"
       shift
       ;;
   -p | -print)
       { [ "$insensitive" ] || [ "$edit" ]; } && error "$(optionsError)"
       print="yes"
       shift
       ;;
   -s | -search)
       [ "$#" -ge 2 ] || error "'$1' option requires an argument"
       [ "$insensitive" ] && error "$(searchError)"
       { [ "$print" ] || [ "$edit" ]; } && error "$(optionsError)"
       search="$2"
       insensitive=off
       shift 2
       ;;
   -t | -tutorials)
       [ "$dir" ] && error "$(dirError)"
       dir="$FOAM_TUTORIALS"
       shift
       ;;
   -*)
       error "Invalid option '$1'"
       ;;
   *)
       # If filename is already set, then exit
       [ "$filename" ] && error "Arguments specified ($#) =/= 1"
       filename="$1"
       shift
       ;;
    esac
done

# Default search directory if not specified
[ "$dir" ] || dir="$FOAM_SRC"

# Disallow '-f', '-o', '-l' if search directory does not include source code
[ "$wmakeFiles" ] && ! isSrcDir "$dir" && \
    error "With search directory '$dir' (not source code), " \
          "cannot use '-files', '-options' or '-lnInclude'"

# Check number of arguments
[ "$#" -eq 0 ] || error "Arguments specified =/= 1 (optional)"

# If filename is not set, check search string is specified
! [ "$filename" ] && ! [ "$search" ] && \
    error "<filename> can only be omitted if a search string is specified " \
          "with the '-search' option"

# If '-f', '-o', '-l' is selected, ensure <filename> is set
! [ "$filename" ] && [ "$wmakeFiles" ] && \
    error "With '-files', '-options' or '-lnInclude', " \
          "<filename> must be specified"

# Find files
files="$(listFiles "$dir" "$filename" "$search" "$insensitive")"

# Ensure there is at least one file
[ "$filename" ] && msgPart="No file '$filename'" || msgPart="No files"
nParams "$files" > /dev/null || error "$msgPart found in '$dir'"

# Select files when more than one is found
files="$(selectFile "$filename" "$files")" || error

{ [ "$wmakeFiles" ] || [ "$edit" ] || [ "$codedFile" ] ; } && \
    [ "$(nParams "$files")" -ne 1 ] && \
    error "With '-files', '-options', '-lnInclude', '-coded' or '-edit', " \
          "a single file must be selected"

# With '-coded' check the file is a *.H file
[ "$codedFile" ] && ! [ "${files##*.}" = "H" ] && \
    error "With '-coded', selected file must be a header file (.H extension)"

# create include text and add lnInclude to wmakeFiles
[ "$codedFile" ] && \
    codeInclude="#include \"${files##*/}\"" && \
    ! echo "$wmakeFiles" | grep -q lnInclude && \
    wmakeFiles="$wmakeFiles lnInclude"

# With '-files', '-options', '-lnInclude' or '-coded', reuse files variable
# for the wmake files
[ "$wmakeFiles" ] &&
    ! files="$(findWmakeFiles "$files" "$wmakeFiles")" && error

# Output
for f in $files
do
    # Handle lnInclude directory output and coded file entries
    [ "${f##*/}" = "lnInclude" ] && \
        writeCoded "$f" "$codedFile" "$codeInclude" && continue

    printf "\nFile: %s\n" "$f"

    # Printing entire files
    [ "$print" ] && \
        printf ">>>\n" && \
        { [ "$numbers" ] && cat -n "$f" || cat "$f" ; } && \
        printf "<<<\n"

    # Opening files in a editor
    [ "$edit" ] && "$edit" "$f"

    # Printing lines matching strings
    [ "$search" ] || continue
    ! grepFile "$search" "$f" "$insensitive" test && \
        echo "Search: no match" && continue
    printf ">>>\n"
    grepFile "$search" "$f" "$insensitive" "$numbers"
    printf "<<<\n"
done