Load an icon source file, remove the references to recompose/pure, then write into the JDL

Very simplistic transform, and won't write anything if the file's not recognised / transformed correctly.
343908
function processIcon({ filePath, relativePath }, destPathRoot) {

    // The patterns we're looking for. Only write the new file if all are met.
    const pureImportRegex = /^import pure from 'recompose\/pure';\s*\n/gm;
    const componentDeclRegex = /let (\w+) = \(props\) =>/;
    const pureWrapRegex = /^((\w+)) = pure\(\1\);\s*\n/gm;

    // We'll const the component declaration while we're at it
    const componentDeclReplacement = 'const $1 = (props) =>';

    const destPath = pathUtils.resolve(destPathRoot, relativePath);

    return fs.readFileAsync(filePath, { encoding: 'UTF8' })
        .then(sourceCode => {

            const pureImportMatch = sourceCode.match(pureImportRegex);
            const componentDeclMatch = sourceCode.match(componentDeclRegex);
            const pureWrapMatch = sourceCode.match(pureWrapRegex);

            if (!(pureImportMatch && componentDeclMatch && pureWrapMatch)) {
                // Could not make sense of this file
                return {
                    filePath,
                    relativePath,
                    error: 'Could not recognise the source',
                };
            }

            // Update the source
            const newSourceCode = sourceCode
                .replace(pureImportRegex, '')
                .replace(pureWrapRegex, '')
                .replace(componentDeclRegex, componentDeclReplacement);

            return fs.writeFileAsync(destPath, newSourceCode, { encoding: 'UTF8' })
                .then(() => ({
                    filePath,
                    relativePath,
                    success: true,
                    className: componentDeclMatch[1],
                }))
        });
}
10777
def refactor_file(self, filename, write=False, doctests_only=False):
        """"""
        input, encoding = self._read_python_source(filename)
        if input is None:
            # Reading the file failed.
            return
        input += u"\n" # Silence certain parse errors
        if doctests_only:
            self.log_debug("Refactoring doctests in %s", filename)
            output = self.refactor_docstring(input, filename)
            if self.write_unchanged_files or output != input:
                self.processed_file(output, filename, input, write, encoding)
            else:
                self.log_debug("No doctest changes in %s", filename)
        else:
            tree = self.refactor_string(input, filename)
            if self.write_unchanged_files or (tree and tree.was_changed):
                # The [:-1] is to take off the \n we added earlier
                self.processed_file(unicode(tree)[:-1], filename,
                                    write=write, encoding=encoding)
            else:
                self.log_debug("No changes in %s", filename)
104752
public void compile() throws JasperException, FileNotFoundException {
        createCompiler();
        if (jspCompiler.isOutDated()) {
            if (isRemoved()) {
                throw new FileNotFoundException(jspUri);
            }
            try {
                jspCompiler.removeGeneratedFiles();
                jspLoader = null;
                jspCompiler.compile();
                jsw.setReload(true);
                jsw.setCompilationException(null);
            } catch (JasperException ex) {
                // Cache compilation exception
                jsw.setCompilationException(ex);
                if (options.getDevelopment() && options.getRecompileOnFail()) {
                    // Force a recompilation attempt on next access
                    jsw.setLastModificationTest(-1);
                }
                throw ex;
            } catch (FileNotFoundException fnfe) {
                // Re-throw to let caller handle this - will result in a 404
                throw fnfe;
            } catch (Exception ex) {
                JasperException je = new JasperException(
                        Localizer.getMessage("jsp.error.unable.compile"),
                        ex);
                // Cache compilation exception
                jsw.setCompilationException(je);
                throw je;
            }
        }
    }
557771
def write(self, symbol, data, prune_previous_version=True, metadata=None, **kwargs):
        
        if data is not None:
            # We only write data if existing data is None or the Timeseries data has changed or metadata has changed
            if self.base_ts.data is None or not are_equals(data, self.base_ts.data) or metadata != self.base_ts.metadata:
                self._do_write = True
        self._write = partial(self._version_store.write, symbol, data, prune_previous_version=prune_previous_version,
                              metadata=metadata, **kwargs)
1302210
def _copy_or_render_source(ext, f, output_dir, render_callback,
                           skip_copy=False):
    
    # Either render a template or copy the source
    dirname = os.path.dirname(f)
    filename = os.path.basename(f)
    for pattern, target, subsd in ext.template_regexps:
        if re.match(pattern, filename):
            tgt = os.path.join(dirname, re.sub(
                pattern, target, filename))
            rw = MetaReaderWriter('.metadata_subsd')
            try:
                prev_subsd = rw.get_from_metadata_file(output_dir, f)
            except (FileNotFoundError, KeyError):
                prev_subsd = None

            render_callback(
                get_abspath(f),
                os.path.join(output_dir, tgt),
                subsd,
                only_update=ext.only_update,
                prev_subsd=prev_subsd,
                create_dest_dirs=True,
                logger=ext.logger)
            rw.save_to_metadata_file(output_dir, f, subsd)
            return tgt
    else:
        if not skip_copy:
            copy(f,
                 os.path.join(output_dir,
                              os.path.dirname(f)),
                 only_update=ext.only_update,
                 dest_is_dir=True,
                 create_dest_dirs=True,
                 logger=ext.logger)
        return f
1338349
function (options, dir, callback) {
  var iconFile = path.join(dir, getPixmapPath(options))
  options.logger('Creating icon file at ' + iconFile)

  fs.copy(options.icon, iconFile, function (err) {
    callback(err && new Error('Error creating icon file: ' + (err.message || err)))
  })
}
758413
protected boolean transform(IResource resource) throws Exception {
        String name = StringUtils.trimToEmpty(resource.getSourcePath());
        
        if (resource.isDirectory() || mojo.isExcluded(name)) {
            return false;
        }
        
        AbstractTransform transform = getTransform(name);
        String targetPath = transform == null ? null : transform.getTargetPath(resource);
        
        if (targetPath != null) {
            File out = mojo.newStagingFile(relocateResource(targetPath), resource.getTime());
            try (OutputStream outputStream = new FileOutputStream(out);) {
                transform.transform(resource, outputStream);
                return true;
            }
        }
        
        return false;
    }
777742
protected File transformInputFile(File from) throws MojoExecutionException {
        // create a temp file
        File tempFile;
        try {
            tempFile = File.createTempFile("dotml-tmp", ".xml");
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "error creating temp file to hold DOTML to DOT translation", e);
        }
        // perform an XSLT transform from the input file to the temp file
        Source xml = new StreamSource(from);
        Result result = new StreamResult(tempFile);
        try {
            Source xslt = new StreamSource(
                    getClass().getClassLoader().getResourceAsStream("dotml/dotml2dot.xsl"));
            transformerFactory.newTransformer(xslt).transform(xml, result);
        } catch (TransformerException e) {
            throw new MojoExecutionException(
                    String.format("error transforming %s from DOTML to DOT file", from), e);
        }
        // return the temp file
        return tempFile;
    }
191478
private static ImmutableMap<Symbol, File> loadDocIdToFileMap(
      final Optional<File> inputFileListFile,
      final Optional<File> inputFileMapFile) throws IOException {
    checkArgument(inputFileListFile.isPresent() || inputFileMapFile.isPresent());

    final Optional<ImmutableList<File>> fileList;
    if (inputFileListFile.isPresent()) {
      fileList = Optional.of(FileUtils.loadFileList(inputFileListFile.get()));
    } else {
      fileList = Optional.absent();
    }

    final Optional<ImmutableMap<Symbol, File>> fileMap;
    if (inputFileMapFile.isPresent()) {
      fileMap = Optional.of(FileUtils.loadSymbolToFileMap(inputFileMapFile.get()));
    } else {
      fileMap = Optional.absent();
    }

    // sanity checks

    if (fileList.isPresent()) {
      // file list may not contain duplicates
      final boolean containsDuplicates =
          ImmutableSet.copyOf(fileList.get()).size() != fileList.get().size();
      if (containsDuplicates) {
        throw new RuntimeException("Input file list contains duplicates");
      }
    }

    // if both a file map and a file list are given, they must be compatible.
    if (fileList.isPresent() && fileMap.isPresent()) {
      if (fileList.get().size() != fileMap.get().size()) {
        throw new RuntimeException("Input file list and file map do not match in size ("
            + fileList.get().size() + " vs " + fileMap.get().size());
      }
      final boolean haveExactlyTheSameFiles =
          ImmutableSet.copyOf(fileList.get()).equals(ImmutableSet.copyOf(fileMap.get().values()));
      if (!haveExactlyTheSameFiles) {
        throw new RuntimeException(
            "Input file list and file map do not containe exactly the same files");
      }
    }

    // output

    if (fileMap.isPresent()) {
      return fileMap.get();
    } else {
      // if we only had a file list as input, we make a fake doc-id-to-file-map using
      // the absolute path as the document ID.  This won't get output, so it doesn't matter
      // that this is a little hacky
      final Function<File, Symbol> fileNameAsSymbolFunction =
          compose(SymbolUtils.symbolizeFunction(), FileUtils.toAbsolutePathFunction());
      return Maps.uniqueIndex(fileList.get(), fileNameAsSymbolFunction);
    }
  }
985126
function writeMappingFile() {
      // The full mapping combines the asset and source map files.
      var fullMapping = {};
      copyObjectProperties(assetFileMapping, fullMapping);
      copyObjectProperties(sourceFileMapping, fullMapping);

      // Sort the keys.
      var sortedMapping = {};
      var sortedAssets = Object.keys(fullMapping).sort();
      sortedAssets.forEach(function(asset) {
        // track which assets were renamed
        // for filename reference replacement
        // (eg. in CSS files referencing renamed images)
        renameInfos.push({
          from: asset,
          fromRegex: new RegExp('\\b' + asset + '\\b', 'g'),
          to: fullMapping[asset]
        });
        sortedMapping[asset] = fullMapping[asset];
      });

      if (options.assetMap) {
        grunt.file.write(options.assetMap, JSON.stringify(sortedMapping, null, 2));
        grunt.log.oklns('Asset map saved as ' + options.assetMap);
      }
    }
239592
function browserifyTransform(file) {
    var chunks = [];

    var write = function(buffer) {
      chunks.push(buffer);
    };

    var end = function() {
      var content = Buffer.concat(chunks).toString('utf8');
      // convention fileName == key for shim options
      var fileName = file.match(/([^\/]+)(?=\.\w+$)/)[0];
      this.queue(commonjsify(content, options[fileName]));
      this.queue(null);
    };

    return through(write, end);
  }
171742
public static void writeCompilationUnit(
      Filer filer,
      SourceBuilder unit,
      Element originatingElement) throws IOException {
    String typename = unit.typename().toString();
    String finalSource = unit.toString();
    try (Writer writer = filer.createSourceFile(typename, originatingElement).openWriter()) {
      writer.append(finalSource);
    }
  }
26785
@GwtIncompatible("Unnecessary")
  public static ImmutableList<JSError> removeDuplicateZipEntries(
      List<SourceFile> sourceFiles, List<JsModuleSpec> jsModuleSpecs) throws IOException {
    ImmutableList.Builder<JSError> errors = ImmutableList.builder();
    Map<String, SourceFile> sourceFilesByName = new HashMap<>();
    Iterator<SourceFile> fileIterator = sourceFiles.iterator();
    int currentFileIndex = 0;
    Iterator<JsModuleSpec> moduleIterator = jsModuleSpecs.iterator();
    // Tracks the total number of js files for current module and all the previous modules.
    int cumulatedJsFileNum = 0;
    JsModuleSpec currentModule = null;
    while (fileIterator.hasNext()) {
      SourceFile sourceFile = fileIterator.next();
      currentFileIndex++;
      // Check whether we reached the next module.
      if (moduleIterator.hasNext() && currentFileIndex > cumulatedJsFileNum) {
        currentModule = moduleIterator.next();
        cumulatedJsFileNum += currentModule.numJsFiles;
      }
      String fullPath = sourceFile.getName();
      if (!fullPath.contains("!/")) {
        // Not a zip file
        continue;
      }
      String relativePath = fullPath.split("!")[1];
      if (!sourceFilesByName.containsKey(relativePath)) {
        sourceFilesByName.put(relativePath, sourceFile);
      } else {
        SourceFile firstSourceFile = sourceFilesByName.get(relativePath);
        if (firstSourceFile.getCode().equals(sourceFile.getCode())) {
          fileIterator.remove();
          if (currentModule != null) {
            currentModule.numJsFiles--;
          }
        } else {
          errors.add(
              JSError.make(
                  CONFLICTING_DUPLICATE_ZIP_CONTENTS,
                  firstSourceFile.getName(),
                  sourceFile.getName()));
        }
      }
    }
    return errors.build();
  }
334720
def writeRegeneratedFile(outFile, makeBackup, checkNoChanges)
      puts "writeRegeneratedFile, #{outFile}, makeBackup = #{makeBackup}, checkNoChanges = #{checkNoChanges}"
      if makeBackup
        backupFileName = makeBackupFile(outFile)
      end
      File.open(outFile, "w") do |f|
        for component in @components do
          f.write(component.output)
        end
      end
      puts " wrote regenerated page to #{outFile}"
      if checkNoChanges
        if !makeBackup
          raise Exception.new("writeRegeneratedFile #{outFile}: checkNoChanges specified, but no backup was made")
        end
        checkAndEnsureOutputFileUnchanged(outFile, backupFileName)
      end
    end
187838
private void cloneExplorerTypeIcons(Map<String, String> iconPaths) throws CmsException {

        for (Map.Entry<String, String> entry : iconPaths.entrySet()) {
            String source = ICON_PATH + entry.getKey();
            String target = ICON_PATH + entry.getValue();
            if (getCms().existsResource(source) && !getCms().existsResource(target)) {
                getCms().copyResource(source, target);
            }
        }
    }
210042
function(file, ast) {
        var content = recast.print(ast, {
            wrapColumn: Number.Infinity
        }).code;

        content = this._updateSourceMap(file, content);

        fs.writeFileSync(file, content);
    }
1248406
public void remove(IConverter converter, Object sourceObject,
			TypeReference<?> destinationType) {
		convertedObjects.remove(new ConvertedObjectsKey(converter,
				sourceObject, destinationType));
	}