time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

sync.js (2209B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2018 The Stdlib Authors.
      5 *
      6 * Licensed under the Apache License, Version 2.0 (the "License");
      7 * you may not use this file except in compliance with the License.
      8 * You may obtain a copy of the License at
      9 *
     10 *    http://www.apache.org/licenses/LICENSE-2.0
     11 *
     12 * Unless required by applicable law or agreed to in writing, software
     13 * distributed under the License is distributed on an "AS IS" BASIS,
     14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15 * See the License for the specific language governing permissions and
     16 * limitations under the License.
     17 */
     18 
     19 'use strict';
     20 
     21 // MODULES //
     22 
     23 var resolve = require( 'path' ).resolve;
     24 var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
     25 var cwd = require( '@stdlib/process/cwd' );
     26 var exists = require( './../../exists' ).sync;
     27 var validate = require( './validate.js' );
     28 
     29 
     30 // MAIN //
     31 
     32 /**
     33 * Synchronously resolves a path by walking parent directories.
     34 *
     35 * @param {string} path - path to resolve
     36 * @param {Options} [options] - function options
     37 * @param {string} [options.dir] - base directory
     38 * @throws {TypeError} first argument must be a string
     39 * @throws {TypeError} options argument must be an object
     40 * @throws {TypeError} must provide valid options
     41 * @returns {(string|null)} resolved path or null
     42 *
     43 * @example
     44 * var path = resolveParentPath( 'package.json' );
     45 */
     46 function resolveParentPath( path, options ) {
     47 	var spath;
     48 	var child;
     49 	var opts;
     50 	var dir;
     51 	var err;
     52 	if ( !isString( path ) ) {
     53 		throw new TypeError( 'invalid argument. First argument must be a string primitive. Value: `' + path + '`.' );
     54 	}
     55 	opts = {};
     56 	if ( arguments.length > 1 ) {
     57 		err = validate( opts, options );
     58 		if ( err ) {
     59 			throw err;
     60 		}
     61 	}
     62 	if ( opts.dir ) {
     63 		dir = resolve( cwd(), opts.dir );
     64 	} else {
     65 		dir = cwd();
     66 	}
     67 	// Start at a base directory and continue moving up through each parent directory until able to resolve a search path or until reaching the root directory...
     68 	while ( child !== dir ) {
     69 		spath = resolve( dir, path );
     70 		if ( exists( spath ) ) {
     71 			return spath;
     72 		}
     73 		child = dir;
     74 		dir = resolve( dir, '..' );
     75 	}
     76 	return null;
     77 }
     78 
     79 
     80 // EXPORTS //
     81 
     82 module.exports = resolveParentPath;