11import os , re , sys
22
33slist = {} # slist[name] is list of rule's sources
4- cmd = {} # cmd[name] is the shell command to run
5- age = {} # age[file] is file's age (larger is older)
4+ cmd = {} # cmd[name] is shell command to run for rule
65
76def main ():
87 for line in open ('makefile' ):
@@ -17,23 +16,21 @@ def main():
1716 cmd [nm ] = cmd .get (nm , '' ) + line
1817 elif line .strip ():
1918 error (f'illegal line in makefile: { line } ' )
20- ages () # compute initial ages
2119 if sys .argv [1 ] in slist :
2220 if not update (sys .argv [1 ]):
2321 print (sys .argv [1 ], 'is up to date' )
2422 else :
2523 error (f'{ sys .argv [1 ]} is not in makefile' )
2624
27- def ages ():
28- entries = sorted (os .scandir (), key = lambda e : e .stat ().st_mtime , reverse = True )
29- for t , entry in enumerate (entries , start = 1 ):
30- age [entry .name ] = t # all existing files get an age
31- for n in slist :
32- if n not in age : # if n has not been created
33- age [n ] = 9999 # make n really old
25+ def mtime (n ):
26+ try :
27+ return os .stat (n ).st_mtime
28+ except FileNotFoundError :
29+ return 0 # mark as old if it doesn't exist
3430
3531def update (n , visited = {}):
36- if n not in age :
32+ ntime = mtime (n )
33+ if n not in slist and ntime == 0 :
3734 error (f'{ n } does not exist' )
3835 if n not in slist :
3936 return 0
@@ -44,14 +41,12 @@ def update(n, visited={}):
4441 update (s )
4542 elif visited [s ] == 1 :
4643 error (f'{ s } and { n } are circularly defined' )
47- if age [ s ] <= age [ n ] :
44+ if mtime ( s ) > ntime :
4845 changed = True
4946 visited [n ] = 2
5047 if changed or len (slist .get (n , [])) == 0 :
5148 print (cmd [n ], end = '' )
5249 os .system (cmd [n ]) # execute cmd associated with n
53- ages () # recompute all ages
54- age [n ] = 0 # make n very new
5550 return 1
5651 return 0
5752
0 commit comments