convert directory to tree-string
17800
function dir2TreeStr(){
    argD = Type.isBoolean(argD) ? "./" : trimAndDelQuotes(argD);
    let dirJson,djOpt;
    try{
        djOpt = {
            // preChars:{
            //     directory: ":open_file_folder: ",
            //     file:":page_facing_up: "
            // },
            exclude:{
                outExcludeDir: true //将过滤掉的文件夹输出
            },
            extChars:{
                directory: " /"
            },
            maxDepth: argM
        };
        dirJson = dir2Json(argD, djOpt);
    }catch(e3){
        errorOut("Gen Json via dir failed: " + e3.toString());
        dirJson = false;
    }
    if(!dirJson){
        if(dirJson===null){
            warningOut("The directory '" + argD + "' is empty! (exclude-filter: .git|.svn|.idea|node_modules|bower_components )");
        }
    }else if(Type.isString(dirJson)){
        warningOut("The directory '" + argD + "' is '" + dirJson + "'");
    }else{
        // 间距配置和上面不一样
        s = Type.isNaN(s) ? 2 : s;
        v = Type.isNaN(v) ? 0 : v;
        jsonName = (djOpt.preChars && djOpt.preChars.directory || "") + argD.replace(/\\/g,"/");
        outputVal = false;
        _doMain(dirJson,true);
    }
}
843413
def _get_src(tree_base, source, saltenv='base'):
    '''
    
    '''
    parsed = _urlparse(source)
    sbase = os.path.basename(source)
    dest = os.path.join(tree_base, sbase)
    if parsed.scheme:
        __salt__['cp.get_url'](source, dest, saltenv=saltenv)
    else:
        shutil.copy(source, dest)
735350
function pathToTree(path, numStemmed) {
  var root;
  var leaf;
  for (var i = numStemmed, len = path.length; i < len; i++) {
    var node = path[i];
    var currentLeaf = [node.id, node.opts, []];
    if (leaf) {
      leaf[2].push(currentLeaf);
      leaf = currentLeaf;
    } else {
      root = leaf = currentLeaf;
    }
  }
  return root;
}
679749
def build_dir_tree(self, files):
        

        def helper(split_files):
            this_dir = {'files' : {}, 'dirs' : {}}
            dirs = defaultdict(list)

            for fle in split_files:
                index = fle[0]; fileinfo = fle[1]
                if len(index)  == 1:
                    fileinfo['path'] = index[0] # store only the file name instead of the whole path
                    this_dir['files'][fileinfo['path']] = fileinfo
                elif len(index) > 1:
                    dirs[index[0]].append((index[1:], fileinfo))

            for name,info in dirs.iteritems():
                this_dir['dirs'][name] = helper(info)
            return this_dir
        return helper([(name.split('/')[1:], file_info) for name, file_info in files.iteritems()])
1264835
function _rmdirpSync (directory) {

			if ("undefined" === typeof directory) {
				throw new ReferenceError("missing \"directory\" argument");
			}
				else if ("string" !== typeof directory) {
					throw new TypeError("\"directory\" argument is not a string");
				}
				else if ("" === directory.trim()) {
					throw new Error("\"directory\" argument is empty");
				}
			else if (isDirectorySync(directory)) {

				readdirSync(directory).forEach((_file) => {

					const file = join(directory, _file);

					if (isDirectorySync(file)) {
						_rmdirpSync(file);
					}
					else {
						unlinkSync(file);
					}

				});

				rmdirSync(directory);

			}

		}
269395
def make_file_system_tree(root_folder, _parent=None):
    
    root_node = Node(os.path.basename(root_folder), _parent)
    root_node.path = root_folder
    for item in os.listdir(root_folder):
        item_path = os.path.join(root_folder, item)
        if os.path.isfile(item_path):
            file_node = Node(os.path.basename(item), root_node)
            file_node.path = item_path
        elif os.path.isdir(item_path):
            #folder_path = os.path.join(root_folder, item)
            make_file_system_tree(item_path, _parent=root_node)
    return root_node
1203695
async function makeDirTree() {
    console.log('Creating Directory Tree ...');
    let dirTree = {},
        dirs = [],
        relative = '';
    AllFiles = {};
    idx = 0;
    id = 0;

    dirs.push({ name: 'root', type: 'dir', path: `.`, files: {} });
    dirTree['root'] = { name: 'root', type: 'dir', path: `.`, files: {} };
    return new Promise(async(res, rej) => {
        console.log('Reading files ...');
        while (dirs.length > 0) {
            let activeDir = dirs.shift(),
                files = await walkTree(activeDir.path);
            if (files.length > 0) {
                for (const i of files) {
                    let name = i.type === 'dir' ? i.name : idx++;
                    if (i.type === 'dir' && !i.path.match(/node_modules|.git|bower/)) {
                        dirs.push(i);
                    }
                    activeDir.files[name] = i;
                }
            }
            dirTree[activeDir.name] = activeDir;
        }
        dirTree = dirTree.root;
        res([dirTree, AllFiles]);
    })
}
286696
function (options, iterationInfo) {
        // Use the identity for the key name
        var identity;
        if (options.mode === 'list') {
            identity = iterationInfo.relativeFullPath;
            //identity = identity.toLowerCase();
            //find and replace all containments of '/', ':' and '\' within the string
            identity = identity.replace(/\/|\\|:/g, '');
        }
        else if (options.mode === 'tree') {
            identity = iterationInfo.fileName;
            //identity = identity.toLowerCase();
        }
        else
            throw new Error('Unknown mode');

        //remove extention
        identity = identity.substr(0, identity.lastIndexOf('.')) || identity;

        return identity;
    }
1290456
def build_tree_fast(self, new_path=None, seq_type='nucl' or 'prot'):
        """"""
        # Check output #
        if new_path is None: new_path = self.prefix_path + '.tree'
        # Command #
        command_args = []
        if seq_type == 'nucl': command_args += ['-nt']
        command_args += ['-gamma']
        command_args += ['-out', new_path]
        command_args += [self.path]
        # Run it #
        sh.FastTree(*command_args)
        # Return #
        return FilePath(new_path)
650499
function _setDirectoryOpen(treeData, path, open) {
        var objectPath = _filePathToObjectPath(treeData, path),
            directory = treeData.getIn(objectPath);

        if (!objectPath) {
            return {
                needsLoading: true,
                treeData: treeData
            };
        }

        if (isFile(directory)) {
            return;
        }

        var alreadyOpen = directory.get("open") === true;

        if ((alreadyOpen && open) || (!alreadyOpen && !open)) {
            return;
        }

        treeData = treeData.updateIn(objectPath, function (directory) {
            if (open) {
                return directory.set("open", true);
            } else {
                return directory.delete("open");
            }
        });

        if (open && (directory.get("children") === null || directory.get("notFullyLoaded"))) {
            return {
                needsLoading: true,
                treeData: treeData
            };
        }
        return {
            needsLoading: false,
            treeData: treeData
        };
    }
425103
def _mergetree(src, dst):
    '''
    
    '''
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            log.info("Copying folder %s to %s", s, d)
            if os.path.exists(d):
                _mergetree(s, d)
            else:
                shutil.copytree(s, d)
        else:
            log.info("Copying file %s to %s", s, d)
            shutil.copy2(s, d)
419527
function rmdirSync(root) {

  if (typeof root !== 'string') {
    throw new Error('missing root');
  }

  var chunks = root.split(path.sep); // split in chunks
  var chunk = path.resolve(root); // build absolute path
  // remove "/" from head and tail
  if (chunks[0] === '') {
    chunks.shift();
  }
  if (chunks[chunks.length - 1] === '') {
    chunks.pop();
  }

  return rmdirSyncRecursive(chunk, chunks);
}
1199744
async function viaTreesApi(identifier, dir, token) {
	const files = [];
	const {repo, ref} = parseIdentifier(identifier);
	const contents = await api(`${repo}/git/trees/${ref}?recursive=1`, token);
	for (const item of contents.tree) {
		if (item.type === 'blob' && item.path.startsWith(dir)) {
			files.push(item.path);
		}
	}
	files.truncated = contents.truncated;
	return files;
}
800700
def _tree_to_string(cls, root_element, xml_declaration=True, pretty_print=True):
        
        from lxml import etree
        return gf.safe_unicode(etree.tostring(
            root_element,
            encoding="UTF-8",
            method="xml",
            xml_declaration=xml_declaration,
            pretty_print=pretty_print
        ))
1179819
function treeJSON(name, location, timestamp, dir, length, addNameToLoc) {
        location = api.toURLPath(location);
        if (typeof addNameToLoc == 'undefined' || addNameToLoc) {
            location += "/" + name;
        }
        var result = {
            Name: name,
            LocalTimeStamp: timestamp,
            Directory: dir,
            Length: length,
            Location: location ? contextPath +"/sharedWorkspace/tree/file" + location : contextPath +"/sharedWorkspace/tree",
            ChildrenLocation: dir ? (location ? contextPath +"/sharedWorkspace/tree/file" + location + "?depth=1": contextPath +"/sharedWorkspace/tree" + "?depth=1") : undefined,
            Parents: fileUtil.getParents(contextPath +'/sharedWorkspace/tree/file' + location.split('/').splice(0, 2).join('/'), location.split('/').splice(2).join('/')),
            Attributes: {
                ReadOnly: false
            }
        };
        result.ImportLocation = result.Location.replace(/\/sharedWorkspace\/tree\/file/, "/sharedWorkspace/tree/xfer/import").replace(/\/$/, "");
        result.ExportLocation = result.Location.replace(/\/sharedWorkspace\/tree\/file/, "/sharedWorkspace/tree/xfer/export").replace(/\/$/, "") + ".zip";
        return result;
    }
237899
function convert( name, _path, contents ) {
    var rDefine = /(define\s*\(\s*('|").*?\2\s*,\s*\[)([\s\S]*?)\]/ig,
        rDeps = /('|")(.*?)\1/g,
        root = _path.substr( 0, _path.length - name.length - 3 ),
        dir = path.dirname( _path ),
        m, m2, deps, dep, _path2;

    contents = contents.replace( rDefine, function( m, m1, m2, m3 ) {
        return m1 + m3.replace( rDeps, function( m, m1, m2 ) {
            m2 = path.join( dir, m2 );
            m2 = path.relative( root, m2 );

            m2 = m2.replace(/\\/g, '/');
            return m1 + m2 + m1;
        }) + ']';
    });

    return contents;
}
46647
def tree(path, depth=2, topdown=True, followlinks=False, showhidden=False):
    """"""
    rt = []
    for root, dirs, files in os.walk(path, topdown=topdown, followlinks=followlinks):
        if not showhidden and File.is_hidden(root):
            continue

        current_depth = len(os.path.relpath(root, path).split(os.sep))
        if current_depth > depth:
            continue

        if showhidden:
            _tuple = (
                root,
                [File(os.path.join(root, _dir)) for _dir in dirs],
                [File(os.path.join(root, _file)) for _file in files]
            )
        else:
            _tuple = (
                root,
                [File(os.path.join(root, _dir)) for _dir in dirs if _dir[0] != '.'],
                [File(os.path.join(root, _file)) for _file in files if _file[0] != '.']
            )

        rt.append(_tuple)
    return rt