Written on 2 December 2011, 05:41pm
Tagged with: coldfusion
Do you want to know how many lines of code you have in your application? Challenge accepted 🙂
Here’s a 10-minutes, 50-lines ColdFusion script that counts the number of lines in all the files from a given folder.
<cfsetting requesttimeout="300" showdebugoutput="no" />
<cfset initialDir = ExpandPath( '../' )>
<cfset files = 0> <!-- we will store the number of files that we traversed --->
<cfset lines = 0> <!--- this is what we need --->
<cfset localRoot = "E:\your\input\folder" />
<cfset separator = '\'>
<cfset extensions = 'cfm,cfc,htm,html,css,js'> <!-- add here the list of extensions --->
<cfset tick = GetTickCount()> <!--- start the clock --->
<!--- get list of ALL files --->
<cfdirectory action="list" directory="#initialDir#" name="localQuery" recurse="true"/>
<cfoutput query="localQuery">
<cfif type EQ 'File'>
<cfset extension = LCase(listLast(name,".")) /> <!--- get the extension --->
<cfset temp = ListFindNoCase(extensions, extension)>
<cfif temp IS NOT 0> <!--- if the file extension is one in our initial list --->
<cfset path = directory & separator & name>
<cfset files = files + 1>
<cfif FileExists(path)>
<cftry>
<cffile action="read" file="#path#" variable="content" charset="utf-8">
<cfcatch type="all">Error reading file</cfcatch>
</cftry>
<cfset content = replace(content,Chr(10),Chr(13),"ALL")/> <!--- replace all LFs with CRs --->
<cfset content = replace(content,Chr(13)&Chr(13),Chr(13),"ALL")/> <!--- replace all double CRs with single CRs --->
<!---
...and here is most important part:
we remove ALL the other characters that are NOT CR (\r)
we end up with a string containing ONLY the CRs
we simply count the length of this string and then add 1
--->
<cfset thisFileLines = Len( REReplace( content, "[^\r]+", "", "ALL" ) ) />
<cfset thisFileLines = thisFileLines + 1>
<cfset lines = lines + thisFileLines>
File #path# has <strong>#thisFileLines#</strong> lines<br />
</cfif>
</cfif> <!--- end if extension --->
</cfif><!--- end if type file --->
</cfoutput>
<cfset tock = GetTickCount()> <!--- stop the clock --->
<cfset time = round((tock-tick)/1000)>
<cfoutput><hr />There are <strong>#lines#</strong> lines in #files# files. Search took #time# seconds.</cfoutput>
I got:
There are 101637 lines in 527 files. Search took 3 seconds.
See also