Differenza tra due sottoalberi del file system (Prova pratica 22-07-2011)

From Sistemi Operativi
Jump to navigation Jump to search
Esercizio 2 Script bash o Python: (10 punti):
Siano date due sottoalberi del file system (il programma e' pensato per due versioni di una gerarchia sorgente).
Lo script deve cercare i file .c e .h presenti nei due sottoalberi evidenziando:

– quali sono presenti in un solo sottoalbero
– quali sono presenti in entrambi i sottoalberi ma hanno contenuto differente.

Es:
cmpsource so.1.0 so.1.1
so.1.0/file.c not in so.1.1
so.1.0/p/q/search.c so.1.1/p/q/search.c differ
so.1.1/h/head.h not in so.1.0

(L'ordine delle segnalazioni in output non e' importante).

Soluzione di Federico Giuggioloni in BASH

#!/bin/bash

if [[ $# < 2 ]] ; then
   echo "Usage: cmpsource dir1 dir2"
   exit 1
fi

DIR1=$1
DIR2=$2

if [[ $DIR1 != */ ]] ; then
   DIR1="${DIR1}/"
fi

if [[ $DIR2 != */ ]] ; then
   DIR2="${DIR2}/"
fi

RIS1=`find $DIR1 -regex "^.*\.[hc]$" | sort | cut -d "/" -f 2-`
RIS2=`find $DIR2 -regex "^.*\.[hc]$" | sort | cut -d "/" -f 2-`

IN1=`comm -2 -3 <(echo "$RIS1") <(echo "$RIS2")`
IN2=`comm -1 -3 <(echo "$RIS1") <(echo "$RIS2")`
COMMON=`comm -1 -2 <(echo "$RIS1") <(echo "$RIS2")`

echo

for NAME in `echo "$IN1"` ; do
   echo "${DIR1%?}${NAME} not in ${DIR2}"
done

echo

for NAME in `echo "$IN2"` ; do
   echo "${DIR2%?}${NAME} not in ${DIR1}"
done

echo

for NAME in `echo "$COMMON"` ; do
   if ! cmp -s ${DIR1%?}${NAME} ${DIR2%?}${NAME}
   then echo "${DIR1%?}${NAME} differs from ${DIR2%?}${NAME}"
   fi
done

echo

exit 0

Soluzione di Federico Giuggioloni in Python 3

#!/usr/bin/env python3
import os
import sys
import filecmp

dir1 = sys.argv[1]
dir2 = sys.argv[2]

lendir1 = len(dir1)
lendir2 = len(dir2)

list1 = []
list2 = []

for dirpath, dirnames, filenames in os.walk(dir1):
   for filename in sorted(filenames):
      if filename.endswith(".c") or filename.endswith(".h"):
         list1.append((os.path.join(dirpath, filename))[lendir1:])

for dirpath, dirnames, filenames in os.walk(dir2):
   for filename in sorted(filenames):
      if filename.endswith(".c") or filename.endswith(".h"):
         list2.append((os.path.join(dirpath, filename))[lendir2:])

for name in list1:
   if name not in list2:
      print(dir1 + name + " not in " + dir2)

for name in list2:
   if name not in list1:
      print(dir2 + name + " not in " + dir1)
   if name in list1:
      if not filecmp.cmp(dir1 + name, dir2 + name):
         print(dir1 + name + " differs from " + dir2 + name)